需要用java做一个和VC的socket的通信程序。格式定义如下:
消息头:
第1~4字节  用字节数表示的消息头的长度(13)
第5~8字节  用字节数表示的消息内容长度 (例如:30)
第9字节  服务类型:1为响应,2为请求
第10~11字节 源系统代号   (例如:ab)
第12~13字节 目的系统代号  (例如:cd)
消息内容:
xml格式1、应该如何封装发送的消息?
2、接受到消息之后,如何解析消息头,把各项信息还原出来?谢谢啦

解决方案 »

  1.   

    传递xml还是看看 SOAP 协议吧。
      

  2.   

    1. 通过ByteArrayOutputStream来构造一个DataOutputStream,按照顺序把各个参数写到DataOutputStream里面,参考API。4字节数用writeInt(int v);1字节数用writeByte(int v);
    内容的xml先转成String,用writeBytes(String s)。全部写入后,用ByteArrayOutputStream中的toByteArray()方法就可以得到封装好的byte[],就可以用socket发了。2.从socket的InputStream读的时候,先读前13个byte,得到一个byte[13].再构造ByteArrayInputStream和DataInputStream,用DataInputStream的read方法把返回的参数都读出来,不过一定要按顺序读。按照得到的消息内容长度,再从socket的InputStream读后面的消息体。给分啊!!!
      

  3.   

    不好意思,SOAP 协议是通过 HTTP 来通讯的。
      

  4.   

    首先你的有一个socket吧 地址 端口写上
    然后 需要一个OutputStream out = socket.getOutputStream()
    out.write( 组好的包)
    然后 out.flush();就发完啦还需要一个 InputStream in = new DataInputStream( sock.getInputStream() )
    byte headBytes[]= new new byte[13];
    in.read(headBytes);就读啦;
    然后将读的解析一下看你想要啥就可以了
    俺理解的有没有问题~~~
      

  5.   

    谢谢大家:)
    基本的发送接收操作是明白的,目前就是不太清楚怎么解析消息头。
    例如对方传过来的消息头的格式如下:
    第1~4字节  用字节数表示的消息头的长度(13)
    第5~8字节  用字节数表示的消息内容长度 (例如:30)
    第9字节  服务类型:1为响应,2为请求
    第10~11字节 源系统代号   (例如:ab)
    第12~13字节 目的系统代号  (例如:cd)收到byte数组后,如何来解析才能得到各项内容?
    本人有点菜,多谅解哈
      

  6.   

    第1~4字节  用字节数表示的消息头的长度(13)
    协议方面可能你得清楚对方是怎么传的,数据类型,如int形式的高位还是低位在前等等。
    对于13,如果对方是按0013送过来的,你只需要把前4字节转成整数即可,
    Integer.parseInt(new String(fist4BytesArray));
      

  7.   

    class Head {
        public int headLength;
        public int contentLength;
        public byte serveType;
        pulbic String srcCode;
        public String dCode;}
    然后 需要一个OutputStream out = socket.getOutputStream()
    out.write(headLength)第1~4字节
    out.write(contentLength)第5~8字节
    out.write()
    然后 out.flush();就发完啦还需要一个 InputStream in = new DataInputStream( sock.getInputStream() )
    byte headBytes[]= new new byte[13];
    in.read(headBytes);就读啦;
    然后将读的解析一下看你想要啥就可以了
    俺理解的有没有问题~~~
      

  8.   

    class Head {
        private int headLength;
        private int contentLength;
        private byte serveType;
        private String srcCode;
        private String dCode;
        public Head(...) {...}
        public writeHead(OutputSteam out) {
            out.write(headLength)第1~4字节
            out.write(contentLength)第5~8字节
            out.write()
        }
        public readHead(InputStream in) {
            ...
        }}或者可以试试对象序列化ObjectOutputStream 只是个想法 自己试试吧