Java socket packet communication (2) Encapsulation of packets, socket packets

Source: Internet
Author: User
Tags array to string

Java socket packet communication (2) Encapsulation of packets, socket packets

Yesterday we talked about how to establish a socket communication server and client. Today we will talk about how to encapsulate packets.

I will not elaborate on what is a message here. If you are not clear about it, you can check the information yourself. The main parts of the message we want to talk about today are as follows:

3-bit synchronous check bit + 8-bit message length + packet header + packet style + 32-bit MD5 check bit

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> James </Name> </ROOT> B251AB76B11114DB176023A0AA27A524

Note:

The above 0X110X120X13 is the same part of the three-digit hexadecimal system. For your understanding, we will thank it in the form of characters. 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> Yes packet header. That is, the information contained in each message. <Name> Zhang San </Name> is a newspaper style. B251AB76B11114DB176023A0AA27A524 is the encrypted data.

I will write in the next article about how to convert an object to an xml format. This article mainly describes how to convert the preceding strings into bytes and how to send and receive packets.

1. Create a message object

Public class SocketPacket {private String bodyLen; private String body; private String syncStr; private String md5; public String getBodyLen () {return bodyLen;} public String getBody () {return body ;} public String getSyncStr () {return syncStr;} public String getMd5 () {return md5;} public void setBodyLen (String bodyLen) {this. bodyLen = bodyLen;} public void setBody (String body) {this. body = body;} public void setSyncStr (String syncStr) {this. syncStr = syncStr;} public void setMd5 (String md5) {this. md5 = md5;} public byte [] getByteStream () throws UnsupportedEncodingException {byte [] bodyBytes = this. body. getBytes ("gbk"); // get the byte array of the body int bodyLength = bodyBytes. length; int socketLength = 3 + bodyLength + 8 + 32; byte [] soc = new byte [socketLength]; // Add check data int index = 0; soc [0] = 0x11; soc [1] = 0x12; soc [2] = 0x13; index + = 3; // Add an 8-bit message length (the usage of NumberFormat is also introduced in my blog) NumberFormat numberFormat = NumberFormat. getNumberInstance (); numberFormat. setMinimumIntegerDigits (8); numberFormat. setGroupingUsed (false); byte [] num = numberFormat. format (socketLength ). getBytes (); for (int I = 0; I <8; I ++) {soc [index ++] = num [I];} // Add the body content for (int I = 0; I <bodyLength; I ++) {soc [index ++] = bodyBytes [I];} // Add the md5 Verification Code byte [] md5Bytes = this. md5.getBytes (); for (int I = 0; I <num. length; I ++) {soc [index ++] = md5Bytes [I];} return soc;} // string public String 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); return syncStr + socketLength + body + md5;} // convert the byte array to string public String bytesToString (byte [] bytes, int start, int end) {String str = ""; if (bytes. length <end-start) {return str;} byte [] bs = new byte [end-start]; for (int I = 0; I <end-start; I ++) {bs [I] = bytes [start ++];} str = new String (bs); return str;} public String toString () {return this. syncStr + this. bodyLen + this. body + this. md5 ;}}

2. Tool for encapsulation of message sending and receiving

/*** Message sending */public class SockeUtil {Socket socket = null; public SockeUtil (String ip, int port) throws UnknownHostException, IOException {socket = new Socket (ip, port);} // public SocketPacket sentSocket (SocketPacket socketPacket) throws UnsupportedEncodingException, IOException {SocketPacket sPacket = new SocketPacket (); OutputStream output = null; InputStream input = null; // synchronize the string (3 byte) byte [] sync = null; // byte [] bodyLen = null; // 8-Bit Length byte [] body = null; // content byte [] md5 = null; // MD5 output = socket. getOutputStream (); // write data to send message output. write (socketPacket. getByteStream (); // obtain the data input = socket returned by the server. getInputStream (); sync = this. streamToBytes (input, 3); bodyLen = this. streamToBytes (input, 8); String lenString = new String (bodyLen); int len = Integer. valueOf (lenString); body = this. streamToBytes (input, len); md5 = this. streamToBytes (input, 32); sPacket. setSyncStr (new String (sync, Charset. forName ("gbk"); socketPacket. setBodyLen (new String (bodyLen, Charset. forName ("gbk"); socketPacket. setBody (new String (body, Charset. forName ("gbk"); socketPacket. setMd5 (new String (md5, Charset. forName ("gbk"); return sPacket;} public byte [] streamToBytes (InputStream inputStream, int len) {/*** inputStream. read (to be copied to the byte array, the start position subscript, the length to be copied) * after this method is read, the input subscript is automatically moved back, the next read Time starts from the subscript that was moved after the last read. * therefore, after each read, you do not need to specify the starting subscript */byte [] bytes = new byte [len]; try {inputStream. read (bytes, 0, len);} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} return bytes ;}}

3. encapsulate a class for sending call packets:

Public String socket (SocketPackage socketPackage) throws UnsupportedEncodingException {SocketClient socketClient = null; try {socketClient = new SocketClient (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 message sending exception, message sent:" + new String (socketPackage. getByteStream (), "GBK");} catch (UnsupportedEncodingException e1) {log. error ("socket converts socketPackage into a string exception. socketPackage information:" + socketPackage. getByteStream (); e1.printStackTrace ();} e. printStackTrace ();} String result = ""; try {result = new String (s. getStream (), "GBK");} catch (UnsupportedEncodingException e) {log. error ("socket converts socketPackage into a string exception. socketPackage information:" + socketPackage. getByteStream (); e. printStackTrace ();} return result ;}

In this way, we can send messages and receive messages! Give it a try! Pai_^

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.