当Socket.EndRead()返回0时?

时间:2014-11-11 04:42:51

标签: c# sockets tcpclient

在异步客户端的MSDN example中,以这种方式调用EndRead:

private static void ReceiveCallback( IAsyncResult ar ) {
        try {
            // Retrieve the state object and the client socket 
            // from the asynchronous state object.
            StateObject state = (StateObject) ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0) {
                // There might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));

                // Get the rest of the data.
                client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
                    new AsyncCallback(ReceiveCallback), state);
            } else {
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1) {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
}

bytesRead怎么可能为零?根据文档EndReceive被阻止,直到连接关闭。 <EOF>是否是Socket.BeginReceive的有效缓冲区终止符? 该连接似乎只是因为客户端被关闭而被关闭了#34;。这是对的吗?

1 个答案:

答案 0 :(得分:1)

这就是一般的流,特别是TCP套接字的工作原理。您继续读取它们,直到读取操作完成但返回的字节数为0. 0是代码的信号,表示没有更多数据可供读取。

对于TCP套接字的流(例如,从TcpClient.GetStream()返回的一个流),协议知道当远程端使用&执行关闭操作时,将无法读取更多数据。 #34;发送&#34;或&#34;两者&#34;作为参数。这就是远程端实际发出信号发送数据的方式。

在本地端,这被解释为流的结尾。如上所述,通过完成读取操作,其中读取的字节数为0,反过来会向您的代码报告。