How can we find that all bytes receive from sockets?

牧云@^-^@ 提交于 2019-11-30 09:10:22

问题


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() method when Scoket.Send(byte[]) method is complete.

List<byte> LBytes = new List<byte>();
do
{
System.Threading.Thread.Sleep(50);
BytesRead = obj_socket.Receive(obj_buffer, 0);
LBytes.Append(obj_buffer);
} while (BytesRead != 0);

because when we disconnect the socket , socket reads 0 bytes . for example we sent 100,000 bytes , and we should receive 100,000 bytes . How you do this?


回答1:


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;
}


来源:https://stackoverflow.com/questions/5065132/how-can-we-find-that-all-bytes-receive-from-sockets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!