C# Async Sockets Server Receive Problems

后端 未结 1 779
夕颜
夕颜 2020-12-06 03:33

I have implemented my Server application regarding this post here: http://www.codeguru.com/csharp/csharp/cs_network/sockets/article.php/c8781#Client1

Sum up: I am us

相关标签:
1条回答
  • 2020-12-06 04:33

    TCP is stream based and not message based. One Read can contain any of the following alternatives:

    • A teeny weeny part of message
    • A half message
    • Excactly one message
    • One and a half message
    • Two messages

    Thus you need to use some kind of method to see if a complete message have arrived. The most common methods are:

    • Add a footer (for instance an empty line) which indicates end of message
    • Add a fixed length header containing the length of the message

    Update

    Simple example having just length as header.

    Server side:

    var buffer = binaryFormmater.Serialize(myobj);
    var length = buffer.Length;
    networkStream.Send(length);
    networkStream.Send(buffer, 0, buffer.Length);
    

    Client side:

    var header = new buffer[4];
    // TODO: You need to make sure that 4 bytes have been read.
    networkStream.Read(header, 0, 4);
    var length = BitConverter.ToInt32(buffer);
    
    var readbuffer= new byte[65535];
    var bytesLeft = length;
    var messageStream = new MemoryStream();
    while (bytesLeft > 0)
    {
         var read = networkStream.Read(readbuffer, 0, bytesLeft);
         messageStream.Write(readbuffer, 0, read);
         bytesLeft -= read,
    }
    
    messageStream.Seek(0, SeekOrigin.Begin);
    MyMessage msg = (MyMessage)binForm.Deserialize(messageStream);
    
    0 讨论(0)
提交回复
热议问题