Solve socket dip Problem--c# code

Source: Internet
Author: User

Solve socket dip Problem--c# code

The night before yesterday, a colleague asked me to send a message if too often the receiver will have the message overlap, because at that time, no more thinking of the first reaction is the result of multithreading caused by the data is not synchronized, let him add a line lock to fix. Later came home slowly thinking this and locking does not matter, if it is multi-threaded, the message will only be overwritten AH. Later on the Internet search socket message overlap, and later learned that this belongs to the socket DIP packet.

Simple with your own understanding of the socket DIP packet.

The socket packet is simply said to be: The socket sender sends a message very frequently causing the receiver to receive a message that is two or more messages in the previous connection. As for the detailed introduction can Baidu related information to understand.

Sockets are generally divided into two types:

1. Socket sender: When the socket sends a message, it is stored in a buffer, waiting for the buffer to be full or waiting for the time to be sent out.

2, Socket Receiver: The receiver is generally due to the failure to retrieve data from the socket buffer in time, resulting in the subsequent data accumulated together.

This only introduces the sender-led

Sender processing methods are generally two types of

1, Nodelay=true,nodelay is using the Nagle algorithm, this is a socket to provide a method, I try to use alone feel little effect, there is a delay after the transmission, so that will not cause the dip bag.

2. The subcontracting method is the first 4 bytes of the sending message plus the message length, and the receiving party resolves the length and then obtains the message based on the message length after receiving the data. Each time the received data has a total length loop through the message in the total length.

directly on the code.

Subcontracting method Send-side main code

1            //test the message to be sent2             string[] SendData =New string[] {"xx"," One","2222","333333","44444444","I love China China Love Me hahaha China","Greater China you"};3             intUserKey =Listconnect.selectedindex;4             if(UserKey <0)5             {6MessageBox.Show ("Please select the person you want to send!");7             }8 9             ElseTen             { One                 //to test a loop to send a message A                  for(inti =0; I <7; i++) -                 { -  the                     //Get message content -                     byte[] msg =Encoding.UTF8.GetBytes (Senddata[i]); -  -                     byte[] Array =New byte[MSG. Length +1+4]; +  -                     //The first byte represents a message type 1: Text message 2: File +array[0] =1; A                     //writes a message length to 4 bytes from the second 2 bytes atConvertinttobytearray (Msg. Length,refarray); - -                     //byte copy -Buffer.blockcopy (MSG,0, Array,5, Msg. Length); in                     //socket sends the current connected socket list of DIC store - Dic[userkey]. Send (array); to  +  -                 } the}

Receive-side message part code

1                //Loop listen to receive messages2                  while(flag)3                 {4                     byte[] bytes =New byte[1024x768*1024x768*2];5 6                     //Total message Length7                     intDatalength =0;8Datalength = Serversocket.receive ( outbytes);9 Ten                     //Judging message Types One                     if(bytes[0] ==1) A                     { -  -                         //solve the Dip problem code the  -                         intMsgbeginindex =-1; -                         intMsgendindex =-1; -                         intMsglength =0; +                         intn =0; -  +                         /** Below are the contents of the received packet in byte[] A                          *  at 0=1 represents message type - 1=2 Message Length (message length of 4 bytes) - 2=0 . - 3=0 . - 4=0 . - 5=48 Message Content in 6=48 . - The following is the same as the previous structure, the dip package causes two messages to stick together to 7=1 + 8=2 - 9=0 the 10=0 * 11=0 $ 12=49Panax Notoginseng 13=49 -                         ... the                         ******/ +                          while(N <datalength) A                         { the                             //Extract the message length 4 bytes separately +                             byte[] Msglengthbyte =New byte[4]; -  $                              for(inti =0; I <4; i++) $                             { -                                 //Msgendindex: The index at which the message ends -                                 //the first message length may be 2; the                                 //the second length may be 8. Index here to use Msgendindex; -                                 //last +2+i: The length of each message record is from the second byte of this message until the fourth byteWuyi  the                                 //the Msgendindex default =-1 message length is located at the beginning of the second byte after the end of the previous message; -                                 //-1+2=1 This guarantees the length of the first message and the location of the subsequent message length WuMsglengthbyte[i] = Bytes[msgendindex +2+i]; -                             } About                             //turn message length to int $Msglength = Bitconverter.toint32 (Msglengthbyte,0); -  -                             //message Start index = end of message index +6 (the preceding 5 bytes are not the message content message content is starting with the 6th byte; +6 is because the Msgendindex index is starting from-1) -Msgbeginindex = Msgendindex +6; A  +                             //message End Index position = Cursor Index start position + message length-1 because the message start index itself is the message start index message ends must be subtracted from the start index theMsgendindex = Msgbeginindex + Msglength-1; -  $                             //Get message content the                             stringReceive =Encoding.UTF8.GetString (Bytes, msgbeginindex, msglength); the                             if(Receive! =NULL) the                             { theTxtlog.begininvoke (NewAction (() = -                                 { in                                     theTxtlog.appendtext (DateTime.Now.ToString ("HH:mm:ss") +" "+ Receive +"\ r \ n"); the                                 })); About                             } the  the                           the  +n = msgendindex +1; -                         } the                     }Bayi  the  the                     //File Receive -                     Else if(bytes[0] ==2) -                     { the                     } the}

Solve socket dip Problem--c# code

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.