When the socket received data, will be based on the size of the buffer 1.1 points of reception data, such as: the other side sent a 1M of data, but, the local buffer only 1024 bytes, that means that the socket needs to repeat many times to really collect this logic on a whole message. The other side sent 5 2 characters of the message, the local buffer (size 1024 bytes) will be all of these 5 messages under the bag ...
So, how to deal with it. Here's a simple text message to Demo
According to the situation described above, the most important key lies in the processing of the following 3 factors the end of the message when the message is received. What to do when the end tag is not in this buffer
I put the core algorithm to write a good post: StringBuilder sb = new StringBuilder (); This is used to save the message that has been received, but has not yet ended
public void ReceiveMessage (object state)//This function will be run as thread
{
Socket socket = (socket) state;
while (true)
{
byte[] buffer = new Byte[receivebuffersize]; Buffer size, here is 1024
int Receivedsize=socket. Receive (buffer);
String rawmsg=system.text.encoding.default.getstring (buffer, 0, receivedsize);
int rnfixlength = Terminatestring.length; This refers to the length of the message Terminator, which is RN
for (int i=0;i<rawmsg.length;)//traversal of the entire buffer text received
{
if (i <= rawmsg.length-rnfixlength)
{
if (rawmsg.substring (i, rnfixlength)!= terminatestring)//non-message terminator, add SB
{
Sb. Append (Rawmsg[i]);
i++;
}
Else
{
This. Onnewmessagereceived (sb.) ToString ());//Found message terminator, triggering message receive completion event
Sb. Clear ();
i + = rnfixlength;
}
}
Else
{
Sb. Append (Rawmsg[i]);
i++;
}
}
}
}
How this component is used: a2dtcpclient client = new A2dtcpclient ("127.0.0.1", 5000);
Client. newmessagereceived + = new messagereceived (client_newmessagereceived);
Client. Connect ();
Client. Send ("HELLO");
Client. Close ();
static void Client_newmessagereceived (String msg)
{
Console.WriteLine (msg);
}
Component Code Downloads
This article link: http://www.cnblogs.com/aarond/p/Socket111.html, reprint please specify.