我正在尝试在 C# 中编写一个异步套接字。我阅读了很多 msdn 文章并找到了这两个示例:server,client。
我理解示例代码并使用它来实现我自己的异步套接字。在示例中,服务器检查<EOF>
以确定流的结尾并发送响应。我想知道流结束时不检查特殊文字。我的想法是递归地检查(bytesRead > 0)
和调用。handler.BeginReceive()
请参阅以下内容:
原来的
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));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1) {
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content );
// Echo the data back to the client.
Send(handler, content);
} else {
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
我的点子
if (received > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, received));
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
else
Send(handler, state.sb.ToString());
如果我用我的零件替换原始零件,程序将停止运行。我猜客户端在 in 之后执行并EndSend()
阻止SendCallback()
线程。我怎么能通过这个?是否有必要使用确定流结束的令牌?receiveDone.WaitOne()
StartClient()
还有其他好的示例代码吗?我刚找到那两个。
(证据。服务器应该接收在线客户端并将它们从这个缓冲区中放入一个循环缓冲区,他应该使用多线程读取和处理记录。)
编辑
如果我使用以下功能:
if (receive > 0)
state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, receive));
if (receive == StateObject.BufferSize)
state.listener.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
else
Send(state.listener, state.sb.ToString());
一切工作正常,我猜。可以吗?还是想念我什么?
如果我将这两个 if 结合起来,它将不再起作用。为什么?
if(receive > 0 || receive == StateObject.BufferSize)
->if(receive > 0) // Not working.