Android Socket send and receive data problem: After sending the data received to always sticky packet

Source: Internet
Author: User

First of all, the concept of sticky bag: When the transmission is two separate packets, two times sent, but received when two packets were once received.
In the previous WinCE Socket programming, do also have to deal with the problem of sticky bag, did not expect to encounter under the Android.
First of all, you can avoid such problems from the sender, for example: (1) Call the force brush data to complete the sending function, (2) Set the Send time-out.
1 try to call the flush () function first, but after the operation, the behavior is still
2 Setting the Send timeout is the practice of the Windows platform, but is there a similar setting under Android?
Look at the implementation code of the Socket class: Java.net.socket socket.class file, it is found that there is still a function to complete such a setting. See the following descriptions of functions and variables:

1 /** 2 * Sets this socket ' s {@linksocketoptions#tcp_nodelay} option. 3  */  4  Public voidSettcpnodelay (BooleanOnthrowsSocketException {5Checkopenandcreate (true); 6 impl.setoption (Socketoptions.tcp_nodelay, boolean.valueof (on)); 7}

And

 1  /**    * This boolean option specifies whether data are sent immediately on this socket. /span>3   * as a side-effect this could leads to low PAC Ket efficiency. The  4   * Socket implementation uses the Nagle ' s algorithm to try to reach a higher  5   * Packet efficiency If this option is disabled.  6  */  public  static  final  int  tcp_nodelay = 1; 

In general, you only need to invoke the following code:

1  Public NULL ;   2 // instantiate an object and connect to the  server 3 New Socket ("172.25.103.1", 12589);  

No setup is necessary to complete the communication with the server/client, and I did it at first. So, I met the above problem.

1 // send the packet, the default is false, that is, the client sends the  data using the Nagle algorithm; 2 // However, for programs with high real-time interactivity, it is recommended to change to true, that is, to turn off the Nagle algorithm, which sends  the data every time the client sends the data, regardless of the packet size. 3 clientsocket.settcpnodelay (true);  

See the following more complete Socket initialization and setup process:

1 /** * * * * * * * * * client Socket connects to server through construction method * * * * * * * * * **/  2 Try {  3   //the client Socket can be connected to the server by specifying either an IP address or a domain name, ultimately connecting to the server via an IP address4   //Create a new socket, specifying its IP address and port number5Socket Clientsocket =NewSocket ("172.25.103.1", 12589); 6   //when the client socket receives data, there are two timeouts: 1. The connection server timed out, that is, the connection timed out; 2. After the connection server succeeds, the receiving server data times out, that is, the receive timeout7   //to set the time-out for the socket read data stream8Clientsocket.setsotimeout (5000); 9   //send the packet, the default is false, that is, the client sends the data using the Nagle algorithm;Ten   //However, for programs with high real-time interactivity, it is recommended to change to true, that is, to turn off the Nagle algorithm, which sends the data every time the client sends the data, regardless of the packet size. OneClientsocket.settcpnodelay (true);  A   //when the client socket is set to close, the close () method has a delay of 30 seconds when it works, and if the unsent data is packets sent out in 30 seconds -Clientsocket.setsolinger (true, 30);  -   //sets the send buffer size of the output stream, which defaults to 4KB, or 4096 bytes theClientsocket.setsendbuffersize (4096);  -   //sets the receive buffer size for the input stream, which defaults to 4KB, or 4096 bytes -Clientsocket.setreceivebuffersize (4096);  -   //role: Check the server is active every time, if the server side is not responding for a long time, automatically shut down the client socket +   //client is connected for a long time to prevent server-side invalidation -Clientsocket.setkeepalive (true);  +   //The client sends data to the server to get the client to the server-side output stream AOutputStream Ossend =Clientsocket.getoutputstream ();  atOutputStreamWriter Oswrite =NewOutputStreamWriter (ossend);  -BufferedWriter Bufwrite =NewBufferedWriter (Oswrite);  -   //represents the ability to send single-byte data to the server immediately -Clientsocket.setoobinline (true);  -   //data does not go through the output buffer and is sent immediately -Clientsocket.sendurgentdata (0x44);//"D" in   //write data to the server, write a buffer -   //Note: Here the string must finally contain "\r\n\r\n", tell the server HTTP header has ended, can process the data, otherwise it will cause the following read data blocking to   //in the Write () method, you can define a rule that matches the background to identify the appropriate feature, such as logging in to the login () method, which can be written as write ("login|  leozheng,0603 \r\n\r\n "), for background recognition;  +Bufwrite.write ("login| leozheng,0603 \r\n\r\n ");  -   //The data in the send buffer-the previous call flush () is not valid, it may be called the wrong way!  the Bufwrite.flush ();  * }   $ Catch(unknownhostexception e) {Panax Notoginseng E.printstacktrace ();  -}Catch(IOException e) { the E.printstacktrace ();  +}
1 /** * * * * * * * * * * Socket Client Reads server-side response data * * * * * * * * * **/  2 Try {  3   //serversocket.isconnected Indicates if the connection has been successful4   //To determine if the Socket is in a connected state5   if(true= = serversocket.isconnected () &&false==serversocket.isclosed ()) {  6     //client receives server-side response, reads the server-side input stream to the client7InputStream Isread =Serversocket.getinputstream (); 8     //buffers9     byte[] buffer =New byte[Isread.available ()]; Ten     //Read Buffer One isread.read (buffer);  A     //Convert to String -String Responseinfo =NewString (buffer);  -     //Output in log theLOG.I ("Socket Server", Responseinfo);  -   }   -   //shut down the network - Serversocket.close ();  + }   - Catch(unknownhostexception e) { + E.printstacktrace ();  A}Catch(IOException e) { at E.printstacktrace ();  -}
1 /** * * * * * * * * * * The Socket client connects to the server via the Connect method * * * * * * * * **/  2 Try {  3Socket ServerSocket =NewSocket (); 4   //Use the default connection timeout5Serversocket.connect (NewInetsocketaddress ("172.25.103.1", 12589));//Connection Timeout 3 seconds: serversocket.connect (New Inetsocketaddress ("172.25.103.1", 12589), 3000); 6     7   //Close Socket8 Serversocket.close (); 9 }  Ten Catch(unknownhostexception e) { One E.printstacktrace ();  A}Catch(IOException e) { - E.printstacktrace ();  -}

Finally, the point is: no matter how the Socket is set, the receiver is bound to deal with the problem of sticky packets. That is, when receiving, the docking received data analysis, to see if there is no data or sticky packet phenomenon.

Android Socket send and receive data problem: sent data received always sticky packet

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.