in app development, it is often Use JSON and Server Socket requests that the data returned by the server be reconciled.
to Accurate Warranty no data loss during network transfer , it is common to send request data Send the length of the data to the server before sending. But the length of the data is the need to send full 4-bit integer data to the server.
As an example: sign in with your phone number and verification code
The sending request body is: {"cmd": "Login", "username": "Ceshi", "Code": "123456"}
The length of the data is: 50.
as we all know, a byte has 8 bits. Then the binary rendering of data length 50 is:110010.
the rendering of full 4-bit integer binary is: 00110010 00000000 00000000 00000000.
The OutputStream provides a method of write (int v) that writes int integer data to the input stream. However , the full 4-bit integer write is not done, only the 110010is sent, that is, only 1-bit integer data is sent .
so Dateoutputstream's writeint (int v) is always OK.
not really, because it's not going to be in 110010 complement 0 of the.
need to pass through the NIO inside Bytebuffer. It provides allocate (int capacity) An array of bytes that can be allocated in size.
by Bytebuffer.order (Byteorder bo) low-fill 0.
finally through Putint The length of the data written at the position of 1 bytes.
The following is an example of the complete code:
Import Java.io.*;import java.net.*;import Java.nio.bytebuffer;import Java.nio.byteorder;public class TalkClient { public static void Main (String args[]) {try {socket socket = new Socket ("120.24.60.164", 6010);//The output stream is obtained by the Socket object DataOutput Stream OS = new DataOutputStream (Socket.getoutputstream ());//The input stream is obtained by the socket object and the corresponding BufferedReader object is constructed BufferedReader is = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); String ReadLine = "{\" cmd\ ": \" login\ ", \" username\ ": \" ceshi\ ", \" code\ ": \" 123456\ "}"; byte[] Databuf = Readline.getbytes (); int len = databuf.length; Bytebuffer datalenbuf = bytebuffer.allocate (4);d Atalenbuf.order (Byteorder.little_endian);d atalenbuf.putint (0, Len) ; Bytebuffer sendbuf = bytebuffer.allocate (len + 4); Sendbuf.order (Byteorder.little_endian); Sendbuf.put ( Datalenbuf.array (), 0, 4); Sendbuf.put (databuf, 0, Len);//client request to 120.24.60.164 6010 Port Os.write (Sendbuf.array (), 0, Len + 4);//refresh the output stream so that the server immediately receives the string Os.flush (); SYSTEM.OUT.PRINTLN ("Response:" + is.readline ()); Os.close ();Close the socket output stream is.close (); Close the socket input stream socket.close (); Close socket} catch (Exception e) {System.out.println ("Error:" + e); Error, print error message}}}
Android sends full 4-bit int integer data to server puzzle