Java socket transmits data in byte[] Simple shard ("UTF-8" encoding)

Source: Internet
Author: User
Tags getmessage

The flow we choose is DataOutputStream and DataInputStream, and the next time we explain the differences between the various streams in Java.

1. We create the object first:

1     Private NULL ; 2     Private null;

2. You can then use the incoming socket in the constructor method to define the object you just created:

1      PublicClienthandlethread (socket socket) {2          This. Socket =socket;3          This. Inittimer ();4         Try {5             //Socket.setsotimeout (10000);6 //writer = new BufferedWriter (New OutputStreamWriter (7 //This.socket.getOutputStream (), "UTF-8"));8 //reader = new BufferedReader (New InputStreamReader (9 //This.socket.getInputStream (), "UTF-8"));Ten              OneOutputStream =NewDataOutputStream ( This. Socket.getoutputstream ()); AInputStream =NewDataInputStream ( This. Socket.getinputstream ()); -              -  the}Catch(Exception e) { - e.printstacktrace (); - Logutil.error (E.getmessage ()); -         } +}

3. Send method Definition:

The Simple shard format is:

Defines a byte array byte[] buffer = new byte[1024];

The first byte of the data is stored as a shard definition format:

                 /**                  * 00000000                  * The highest bit represents whether it is the first Shard, the ' 1 ' represents the first shard                  * Sub-high represents whether the last Shard, for ' 1 ' represents the last Shard */                 buffer[0] |= 0X80 ;//Represents the first Shard
Buffer[0] |= 0x40;//represents the last Shard
Of course, can also be based on the need to add a specific definition, you can refer to the network protocol header design, there is a need to view the "Computer network" book.

The method is divided into three kinds of trends:

When the data byte array bytes Size-0<bytes.length<=1023: Without sharding, directly define the slice as the last piece buffer[0] |= 0x40;//is the last shard, send directly

When data byte array bytes Size-1023<bytes.length<=2046, you need to split into two pieces

when the data byte array bytes The size of 2046<bytes.length, the first thing to do is to cut first slices (1023 size), and then according to while (remainsize>buffersize) The loop cuts out the intermediate pieces, and the last remaining amount of data is <=1023, which is the last shard.

Specifically, you can refer to the following code:

1     //Send2      Public voidSend (String data) {3         Try {4             //need to set "UTF-8" encoding to avoid garbled characters caused by Chinese        5             byte[] bytes = (data + "\ r \ n"). GetBytes ("UTF-8");6             intposotion = 0;7             intRemainsize = Bytes.length;//remaining data volume size8             intbuffersize = 1023;//Buffer Data volume size +19             if(Remainsize >buffersize)Ten             { OneRemainsize-=buffersize; A                 byte[] buffer =New byte[1024]; -Buffer[0] = 0;//Initialize -                 /** the * 00000000 - * The highest bit represents whether it is the first Shard, and the ' 1 ' represents the first shard - * The second high represents whether the last Shard, the ' 1 ' represents the last Shard -                  */ +Buffer[0] |= 0X80;//represents the first shard -System.arraycopy (bytes, posotion, buffer, 1, buffersize);  +Posotion + =buffersize; A                  This. Outputstream.write (buffer); at                  This. Outputstream.flush (); -                  -             } -              while(remainsize>buffersize) { -Remainsize-=buffersize; -                 byte[] buffer =New byte[1024]; inBuffer[0] = 0;//Initialize - //buffer[0] |= 0X80;//represents the first shard to //buffer[0] |= 0X40;//represents the last shard +System.arraycopy (bytes, posotion, buffer, 1, buffersize); -Posotion + =buffersize; the                  This. Outputstream.write (buffer); *                  This. Outputstream.flush (); $                 Panax Notoginseng             } -             if(Remainsize > 0) the             { +                 byte[] buffer =New byte[Remainsize+1]; ABuffer[0] = 0;//Initialize the //buffer[0] |= 0X80;//represents the first shard +Buffer[0] |= 0X40;//represents the last shard -System.arraycopy (bytes, posotion, buffer, 1, remainsize); $                  This. Outputstream.write (buffer); $                  This. Outputstream.flush (); -             } -              the //this.writer.write (data + "\ r \ n"); - //This.writer.flush ();WuyiSYSTEM.OUT.PRINTLN ("Send" +data); the}Catch(IOException e) { - Logutil.error (E.getmessage ()); Wu e.printstacktrace (); -         } About  $}

4. The following is the receive processing code:

The point to express is that the socket will be sent according to the order of slices, generally do not cause the order of the slices reversed, of course, more rigorous and better, it is better to increase the serial number and number of packets.

Here's a simple example:

1             Try {2                 //System.out.println (runflag);3 4                 //char chars[] = new char[1024];5                 byteBytes[] =New byte[1024];6                 intLen = 0;7StringBuilder Jsonbuffer =NewStringBuilder ();8String temp =NULL;9                 intindex = 0;Ten //While (len = Reader.read (chars))! =-1) { One //temp = new String (chars, 0, Len); A //if (index = Temp.indexof ("\ n"))! =-1) {//end receive when \ n is encountered - //jsonbuffer.append (temp.substring (0, index)); - //Break ; the //                    } - //jsonbuffer.append (temp); - //                } -                  +                  -                  while(len = inputstream.read (bytes))! =-1) { +temp =NewString (bytes, 1, len-1, "UTF-8"); A                     if(index = temp.indexof ("\ n"))! =-1 && (Bytes[0] &= 0X40) ==0x40) {//end Receive and last Shard when \ n is encountered atJsonbuffer.append (temp.substring (0, index)); -                          Break; -                     } - jsonbuffer.append (temp); -                 } -                  in  -String jsonstring =jsonbuffer.tostring (); to 
......

+}Catch(Exception e) { - Logutil.error (e.tostring ()); the}

Here is a simple judge of whether the last Shard, you can add more rigorous judgment on this basis.

Thank you for your reading, I hope you have some help.

Java socket transmits data in byte[] Simple shard ("UTF-8" encoding)

Related Article

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.