Yesterday we talked about how to set up the socket communication server and client, today we will talk about how to encapsulate the message.
What is the message here I will not elaborate, not clear friends can go to check the information on their own. The message we are going to talk about today is mainly composed of the following parts:
3-bit synchronous check digit + 8-bit message length + message header + Newspaper style + 32-bit MD5 check digit
The basic format is as follows:
0x110x120x1300000232<?xml version= "1.0" encoding= "GBK"? ><root><code>0204</code><date >20141223</Date><No>141223010008152</No><Code>17010001</Code><Name> Zhang San </name></root>b251ab76b11114db176023a0aa27a524
Description
The front 0x110x120x13 is the same part of the 3-bit 16-binary, here for everyone to understand, so in the form of characters Xie out. 00000232 is the message length. <?xml version= "1.0" encoding= "GBK"? ><root><code>0204</code><date>20141223</date ><No>141223010008152</No><Code>17010001</Code></ROOT> is the message header. That is, the information contained in each message. <Name> Zhang San </Name> is newspaper style. b251ab76b11114db176023a0aa27a524 is encrypted data.
A message about how to convert an object to XML format I'll write in the next article, here's how to convert these strings into bytes and how to send and receive messages.
1. Set up the object of the message
Public classSocketpacket {PrivateString Bodylen; PrivateString body; PrivateString Syncstr; PrivateString MD5; PublicString Getbodylen () {returnBodylen; } PublicString GetBody () {returnbody; } PublicString getsyncstr () {returnSyncstr; } PublicString getMd5 () {returnMD5; } Public voidSetbodylen (String bodylen) { This. Bodylen =Bodylen; } Public voidSetbody (String body) { This. BODY =body; } Public voidsetsyncstr (String syncstr) { This. Syncstr =Syncstr; } Public voidSetMd5 (String MD5) { This. MD5 =MD5; } Public byte[] Getbytestream ()throwsunsupportedencodingexception{byte[] Bodybytes = This. Body.getbytes ("GBK");//get a byte array of body intBodylength =bodybytes.length; intSocketlength = 3+bodylength+8+32; byte[] Soc =New byte[Socketlength]; //Add validation Data intindex = 0; soc[0]=0x11; soc[1]=0x12; soc[2]=0x13; Index+=3; //Add 8-bit message length (my blog post also has NumberFormat usage introduction)NumberFormat NumberFormat =numberformat.getnumberinstance (); Numberformat.setminimumintegerdigits (8); Numberformat.setgroupingused (false); byte[] num =Numberformat.format (socketlength). GetBytes (); for(inti = 0;i<8;i++) {Soc[index++]=Num[i]; } //Add Body Content for(inti = 0;i<bodylength;i++) {Soc[index++] =Bodybytes[i]; } //Add MD5 Check code byte[] Md5bytes = This. Md5.getbytes (); for(inti = 0; i < num.length; i++) {Soc[index++] =Md5bytes[i]; } returnSoc; } //byte-loaded transfer message string PublicString getString (byte[] socketbytes) {String Syncstr= This. bytestostring (socketbytes, 0, 3); String Socketlength= This. bytestostring (Socketbytes, 3, 3+8); String Body= This. bytestostring (Socketbytes, 3+8, socketbytes.length-32); String MD5= This. bytestostring (socketbytes,socketbytes.length-32, socketbytes.length); returnsyncstr+socketlength+body+MD5; } //Convert a byte array to a string PublicString bytestostring (byte[] Bytes,intStartintend) {String str= ""; if(bytes.length<end-start) { returnstr; } byte[] bs =New byte[end-start]; for(inti = 0;i<end-start;i++) {Bs[i]= bytes[start++]; } STR=NewString (BS); returnstr; } PublicString toString () {return This. syncstr+ This. bodylen+ This. body+ This. MD5; } }
2. Encapsulate the tool class for sending and receiving messages
/*** Message Sending*/ Public classSockeutil {Socket Socket=NULL; PublicSockeutil (String IP,intPortthrowsunknownhostexception, ioexception{socket=NewSocket (IP, port); } // PublicSocketpacket Sentsocket (Socketpacket socketpacket)throwsunsupportedencodingexception, ioexception{socketpacket spacket=NewSocketpacket (); OutputStream Output=NULL; InputStream input=NULL; //synchronization String (3byte) byte[] sync =NULL;// byte[] Bodylen =NULL;//8-bit length byte[] BODY =NULL;//content byte[] MD5 =NULL;//MD5Output =Socket.getoutputstream (); //Write data Sending messageOutput.write (Socketpacket.getbytestream ()); //obtaining data returned by the serverinput =Socket.getinputstream (); Sync= This. Streamtobytes (input,3); Bodylen= This. Streamtobytes (Input, 8); String lenstring=NewString (Bodylen); intLen =integer.valueof (lenstring); Body= This. Streamtobytes (input, Len); MD5= This. streamtobytes (Input, 32); Spacket.setsyncstr (NewString (Sync,charset.forname ("GBK"))); Socketpacket.setbodylen (NewString (Bodylen,charset.forname ("GBK"))); Socketpacket.setbody (NewString (Body,charset.forname ("GBK"))); SOCKETPACKET.SETMD5 (NewString (Md5,charset.forname ("GBK"))); returnSpacket; } Public byte[] Streamtobytes (InputStream InputStream,intLen) { /*** Inputstream.read (to copy to the byte array, the starting position subscript, the length to be copied) * The method reads the next bidding clubs of input automatically after the next read, or from the last read after the index moved to start reading * So there is no need to set the starting subscript after each reading*/ byte[] bytes=New byte[Len]; Try{inputstream.read (bytes,0, Len); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } returnbytes; }}
3. The class that encapsulates the sending of a call message:
PublicString socket (socketpackage socketpackage)throwsunsupportedencodingexception{socketclient socketclient=NULL;; Try{socketclient=Newsocketclient (IP, port); } Catch(unknownhostexception e) {log.error ("Socket link exception, link information:" +ip+ port); E.printstacktrace (); } Catch(IOException e) {log.error ("Socket IO Exception"); E.printstacktrace (); } socketpackage S=NULL; Try{s=socketclient.sendmsg (socketpackage); } Catch(Exception e) {Try{log.error ("Socket send message exception, send message:" +NewString (Socketpackage.getbytestream (), "GBK")); } Catch(unsupportedencodingexception E1) {Log.error ("Socket will socketpackage to string exception, Socketpackage information:" +Socketpackage.getbytestream ()); E1.printstacktrace (); } e.printstacktrace (); The String result= ""; Try{result=NewString (S.getstream (), "GBK"); } Catch(unsupportedencodingexception e) {log.error ("Socket will socketpackage to string exception, Socketpackage information:" +Socketpackage.getbytestream ()); E.printstacktrace (); } returnresult; }
So we can send the paper and receive the message! Try it now! ^_^
Java Socket message Communication (ii) Packet encapsulation