我有一个异步读取方法...
private void read(IAsyncResult ar) {
//Get the Server State Object
ServerState state = (ServerState)ar.AsyncState;
//read from the socket
int readCount = state.socket.EndReceive(ar);
//check if reading is done, move on if so, trigger another read if not
if (readCount > 0) {
//purge the buffer and start another read
state.purgeBuffer();
state.socket.BeginReceive(state.buffer, 0, ServerState.bufferSize, 0, new AsyncCallback(read), state);
}
else {
//all bytes have been read, dispatch the message
dispatch(state);
}
}
我遇到的问题是,如果连接关闭,read 仅为 0。我怎么说呢,这是该消息的结尾,并将数据传递给调度程序,同时保持套接字打开以接受新消息。
谢谢!
最佳答案
您不应该依赖 TCP 缓冲区中的内容。您必须在某处将传入的字节作为流处理。你无法真正知道它是否完整。只有上面的一层才能知道消息何时完成。
示例: 如果您读取 HTTP 响应,HTTP header 将包含 HTTP 正文中的字节数。所以你知道要读多少。
只有当数据遵循特定协议(protocol)并且您对其进行解释时,您才知道要读取多少内容。想象一下您通过套接字接收一个文件。您收到的第一件事是文件大小。没有它,你永远不知道要读多少。
关于c# - 我如何知道异步套接字读取何时结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9383056/