How can we find that all bytes receive from sockets?

后端 未结 1 1399
长发绾君心
长发绾君心 2021-01-15 19:30

I want to know when we receive all bytes from a socket without Socket.Disconnect() method?

Yet , I use this code to receive all bytes , but i use Socket.Disconnect()

1条回答
  •  长发绾君心
    2021-01-15 19:56

    While the socket is open, there is no way of doing this without causing it to block when it reaches the end (expecting more data).

    There are several ways of doing it:

    • close the socket after sending
    • have some marker that means "end of message" (easy enough with encoded text - 0 being a common choice; tricky when sending arbitrary binary data, though)
    • send a length prefix before the data (100,000 in this case), and stop reading when you get that much

    If it was a NetworkStream, for example, using a length prefix:

    int expecting = //TODO: read header in your chosen form
    int bytesRead;
    while(expecting > 0 && (bytesRead = stream.Read(buffer, 0,
            Math.Min(expecting, buffer.Length))) > 0)
    {
        // TODO: do something with the newly buffered data
        expecting -= bytesRead;
    }
    

    0 讨论(0)
提交回复
热议问题