How can we find that all bytes receive from sockets?
I want to know when we rece开发者_JAVA百科ive 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?
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;
}
精彩评论