Socket Solution Sticky Pack Problem 2

Source: Internet
Author: User

In the Asynserver receive function to increase the reception of judgment, if you receive the request sent by the client, send 10 test packets to the sending side, or continue to receive, the modified receive code as follows:

        Private voidasynreceive () {byte[] data =New byte[1024x768];//Receive Cache            stringReceivestr; string[] Sendarr = Packagebuilder.buildpackage (Ten);//generate send Array, 10 packetsSocket. BeginReceive (data,0, data. Length, socketflags.none, AsyncResult = {                intLength =socket.                            EndReceive (AsyncResult); Receivestr= Encoding.ASCII.GetString (data,0, length);//get the information in the cache//Console.WriteLine (RECEIVESTR);                if(Receivestr = ="1")//The flag character ' 1 ', if received 1, sends the test package to the client, if not 1, continues to accept                {                     for(inti =0; I <Ten; i++) {Console.WriteLine ("{0} times sent:", i);                   Asynsend (Sendarr[i]); //Thread.Sleep ($);                    }                }                Elseasynreceive (); }, NULL); }
View Cosde

where if (receivestr = = "1") is the receiving judgment, if the client receives 1, the test package is sent to the client, if not 1, continues to receive. Because it is sent asynchronously, the Console.WriteLine ("{0} times send:", I); the display may be out of sync with the sending data, but it must have been sent 10 times.

Test, send 10 times, the receiving end received the following results:

Sent 10 times, and only 8 times, from which we can find the 6th and 7th times a sticky bag, two packets are treated as 1 packets received, if you write the unpacking program without considering the sticky packet, then the unpacking loop will be thrown at the 7th time. Of course, a quick way to avoid sticky packets is to send the function of Asynsend (Sendarr[i]), the following add Thread.Sleep (200), reduce the frequency of transmission, but this is not a permanent one, then we go to the client to deal with the sticky packet problem.

The client mainly modifies the Syncreceive method, using StringBuilder to do the receiving, because the StringBuilder is more efficient than string, the string is deleted, the code is as follows:

 string[] Receivearr =New string[Ten];//used to store the received data        intArri=0;//Array bit order         Public Virtual voidsyncreceive () {//StringBuilder sb = new StringBuilder (1024*1024);StringBuilder Receivesb =NewStringBuilder ();//Receive string buffer            stringRECEIVESTR;//for intermediate processing during unpacking            intIndex//bit order, for unpacking            intdatalength;//storing the length of data in a receive package            inti =0; Thread th=NewThread (() =            {                 while(receiveflag) {byte[] buffer =New byte[1024x768]; intR =socket.                    Receive (buffer); stringstr = Encoding.ASCII.GetString (buffer,0, R);//just to showConsole.WriteLine ("data received for {0} times: {1}", i++, str);                    Console.WriteLine ();              Receivesb.append (str); //Store receive string, may save multiple packagesReceivestr =receivesb.tostring (); Index= Receivestr.indexof ("Data:");//There may be multiple "data"                     while(Index >1) {datalength=int. Parse (receivestr.substring (Index-2,2));//data length specified as 2 bytesReceivearr[arri] = receivestr.substring (index, DATALENGTH);//Save the data in the arrayConsole.WriteLine ("array of data saved [{0}]:{1}", arri,receivearr[arri++]); Receivesb.remove (0,Ten+ datalength);//Baotou + Data length byte total 10 bytes "head| H1|38 ", followed by data" Data:xxxxxxxxxxxxxxxxxxxx "Receivestr =receivesb.tostring (); Index= Receivestr.indexof ("Data:");//look for the next "data" if you don't jump out of the loop                    }                                                            //sb. AppendFormat ("{0}", Encoding.ASCII.GetString (buffer, 0, R));                    }            }); Th.                   Start (); }
View Code

The method adds two global variables, Receivearr is an array to hold the received real-time data, which can be used for the foreground display, or directly to the database; Arri is the array bit order and the result is as follows:

, the client received 7 data, and for the first time there were 4 packets glued together, but we still kept the 10 data separately in the string array through the appropriate unpacking.

The client must first send the "1" flag to the client to execute the above program, Synsend ("1");

Source code of the program:

Link: Http://pan.baidu.com/s/1nvfa8lF Password: Zjoa

Sticky bag processing is relatively simple, more troublesome is sub-package, although not common, but also to consider, the following consideration to do a sub-package of processing, the procedure is relatively coarse, if there are shortcomings hope you point out.

Socket Solution Sticky Pack Problem 2

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.