java socket报文通信(二)报文的封装

分布式基础篇

昨天我们谈了怎么建立socket通信的服务端和客户端,今天我们就来谈一谈怎么封装报文。

什么是报文这里我就不在阐述了,不清楚的朋友可以自己去查资料。我们今天要谈的报文主要友以下几个部分组成:

3位同步校验位+8位报文长度+报文头+报文体+32位MD5校验位

基本格式如下:

0X110X120X1300000232<?xml version="1.0" encoding="GBK"?><ROOT><Code>0204</Code><Date>20141223</Date><No>141223010008152</No><Code>17010001</Code><Name>张三</Name></ROOT>B251AB76B11114DB176023A0AA27A524

说明:

  前面的0X110X120X13是3位16进制的同部位,这里为了大家理解,所以就以字符的形式谢出来了。00000232是报文长度。<?xml version="1.0" encoding="GBK"?><ROOT><Code>0204</Code><Date>20141223</Date><No>141223010008152</No><Code>17010001</Code></ROOT>是报文头。即每个报文都包含的信息。<Name>张三</Name>是报文体。B251AB76B11114DB176023A0AA27A524是加密数据。

关于如何将对象转换为xml格式的报文我将在下一篇写,这里主要是给大家如何将如上的这些字符串转化为字节以及如何发送和接收报文。

1.建立报文的对象

[java]  view plain  copy
  1. public class SocketPacket {  
  2.   
  3.     private String bodyLen;  
  4.     private String body;  
  5.     private String syncStr;  
  6.     private String md5;  
  7.     public String getBodyLen() {  
  8.         return bodyLen;  
  9.     }  
  10.     public String getBody() {  
  11.         return body;  
  12.     }  
  13.     public String getSyncStr() {  
  14.         return syncStr;  
  15.     }  
  16.     public String getMd5() {  
  17.         return md5;  
  18.     }  
  19.     public void setBodyLen(String bodyLen) {  
  20.         this.bodyLen = bodyLen;  
  21.     }  
  22.     public void setBody(String body) {  
  23.         this.body = body;  
  24.     }  
  25.     public void setSyncStr(String syncStr) {  
  26.         this.syncStr = syncStr;  
  27.     }  
  28.     public void setMd5(String md5) {  
  29.         this.md5 = md5;  
  30.     }  
  31.       
  32.       
  33.     public byte[] getByteStream() throws UnsupportedEncodingException{  
  34.         byte[] bodyBytes = this.body.getBytes("gbk");//获得body的字节数组  
  35.         int bodyLength = bodyBytes.length;  
  36.         int socketLength = 3+bodyLength+8+32;  
  37.         byte [] soc = new byte[socketLength];  
  38.         //添加校验数据  
  39.         int index = 0;  
  40.         soc[0]=0x11;  
  41.         soc[1]=0x12;  
  42.         soc[2]=0x13;  
  43.         index+=3;  
  44.         //添加8位报文长度(我的博文中也有NumberFormat的用法介绍)  
  45.         NumberFormat numberFormat = NumberFormat.getNumberInstance();  
  46.         numberFormat.setMinimumIntegerDigits(8);  
  47.         numberFormat.setGroupingUsed(false);  
  48.         byte [] num = numberFormat.format(socketLength).getBytes();  
  49.         for(int i = 0;i<8;i++){  
  50.             soc[index++]= num[i];  
  51.         }  
  52.         //添加body内容  
  53.         for(int i = 0;i<bodyLength;i++){  
  54.             soc[index++] = bodyBytes[i];  
  55.         }  
  56.         //添加md5校验码  
  57.         byte [] md5Bytes = this.md5.getBytes();  
  58.         for (int i = 0; i < num.length; i++) {  
  59.             soc[index++] = md5Bytes[i];  
  60.         }  
  61.         return soc;  
  62.     }  
  63.       
  64.     //字节装转报文string  
  65.     public String getString(byte [] socketBytes){  
  66.         String syncStr = this.bytesToString(socketBytes, 03);  
  67.         String socketLength = this.bytesToString(socketBytes, 33+8);  
  68.         String body = this.bytesToString(socketBytes, 3+8, socketBytes.length-32);  
  69.         String md5 = this.bytesToString(socketBytes,socketBytes.length-32,socketBytes.length);  
  70.         return syncStr+socketLength+body+md5;  
  71.     }  
  72.       
  73.     //将字节数组转化为string  
  74.     public String bytesToString(byte [] bytes,int start,int end){  
  75.         String str = "";  
  76.         if(bytes.length<end-start){  
  77.             return str;  
  78.         }  
  79.         byte [] bs = new byte[end-start];  
  80.         for(int i = 0;i<end-start;i++){  
  81.             bs[i] = bytes[start++];  
  82.         }  
  83.         str = new String(bs);  
  84.         return str;  
  85.     }  
  86.       
  87.     public String toString(){  
  88.         return this.syncStr+this.bodyLen+this.body+this.md5;  
  89.     }  
  90.       
  91. }  

2.封装发送和接收报文的工具类

[java]  view plain  copy
  1. /** 
  2.  * 报文发送 
  3.  */  
  4. public class SockeUtil {  
  5.     Socket socket = null;  
  6.     public SockeUtil(String ip,int port) throws UnknownHostException, IOException{  
  7.         socket = new Socket(ip, port);  
  8.     }  
  9.     //  
  10.     public SocketPacket sentSocket(SocketPacket socketPacket) throws UnsupportedEncodingException, IOException{  
  11.         SocketPacket sPacket = new SocketPacket();  
  12.         OutputStream output=null;  
  13.         InputStream input =null;  
  14.         // 同步字符串(3byte)  
  15.         byte[] sync = null//  
  16.         byte[] bodyLen = null// 8位长度  
  17.         byte[] body = null// 内容  
  18.         byte[] md5 = null;  // MD5  
  19.         output = socket.getOutputStream();  
  20.         //写数据发送报文  
  21.         output.write(socketPacket.getByteStream());  
  22.         //获得服务端返回的数据  
  23.         input = socket.getInputStream();  
  24.         sync = this.streamToBytes(input,3);  
  25.         bodyLen = this.streamToBytes(input, 8);  
  26.         String lenString = new String(bodyLen);  
  27.         int len = Integer.valueOf(lenString);  
  28.         body = this.streamToBytes(input, len);  
  29.         md5 = this.streamToBytes(input, 32);  
  30.         sPacket.setSyncStr(new String(sync,Charset.forName("gbk")));  
  31.         socketPacket.setBodyLen(new String(bodyLen,Charset.forName("gbk")));  
  32.         socketPacket.setBody(new String(body,Charset.forName("gbk")));  
  33.         socketPacket.setMd5(new String(md5,Charset.forName("gbk")));  
  34.         return sPacket;  
  35.     }  
  36.       
  37.     public byte[] streamToBytes(InputStream inputStream,int len){  
  38.         /** 
  39.          * inputStream.read(要复制到得字节数组,起始位置下标,要复制的长度) 
  40.          * 该方法读取后input的下标会自动的后移,下次读取的时候还是从上次读取后移动到的下标开始读取 
  41.          * 所以每次读取后就不需要在制定起始的下标了 
  42.          */  
  43.         byte [] bytes= new byte[len];  
  44.         try {  
  45.             inputStream.read(bytes, 0, len);  
  46.         } catch (IOException e) {  
  47.             // TODO Auto-generated catch block  
  48.             e.printStackTrace();  
  49.         }  
  50.         return bytes;  
  51.     }  
  52. }  


3.在封装一个调用报文发送的类:

[java]  view plain  copy
  1. public String socket(SocketPacket socketPacket) throws UnsupportedEncodingException{  
  2.   
  3.         SockeUtil socketUtil = null;;  
  4.         try {  
  5.             socketUtil = new SockeUtil("192.168.13.15"8080);  
  6.         } catch (UnknownHostException e) {  
  7.             log.error("socket链接异常,链接信息:");  
  8.             e.printStackTrace();  
  9.         } catch (IOException e) {  
  10.             log.error("socket IO异常");  
  11.             e.printStackTrace();  
  12.         }  
  13.         SocketPacket s = null;  
  14.         try {  
  15.             s = socketUtil.sentSocket(socketPacket);  
  16.         } catch (Exception e) {  
  17.             try {  
  18.                 log.error("socket发送消息异常,发送信息:" + new String(socketPacket.getByteStream(),"GBK"));  
  19.             } catch (UnsupportedEncodingException e1) {  
  20.                 log.error("socket将socketPackage转为字符串异常,socketPackage信息:" + socketPacket.getByteStream());  
  21.                 e1.printStackTrace();  
  22.             }  
  23.             e.printStackTrace();  
  24.         }  
  25.         String result = "";  
  26.         try {  
  27.              result = new String(s.getByteStream(), "GBK");  
  28.         } catch (UnsupportedEncodingException e) {  
  29.             log.error("socket将socketPackage转为字符串异常,socketPackage信息:" + socketPacket.getByteStream());  
  30.             e.printStackTrace();  
  31.         }  
  32.         return result ;  
  33.   }  

猜你喜欢

转载自blog.csdn.net/zpoison/article/details/78179330
今日推荐