C# 异步套接字程序。未执行接收数据的回调
我遵循这个链接进行异步套接字编程 永远不会调用ReceiveCallback func的Else部分。当存在任何数据时,它将在if(字节读取>0)部分中接收。在if循环中,为了获取其余的数据,再次调用BeginReceive。但根本没有收到对此的回调C# 异步套接字程序。未执行接收数据的回调,c#,sockets,asynchronous,C#,Sockets,Asynchronous,我遵循这个链接进行异步套接字编程 永远不会调用ReceiveCallback func的Else部分。当存在任何数据时,它将在if(字节读取>0)部分中接收。在if循环中,为了获取其余的数据,再次调用BeginReceive。但根本没有收到对此的回调 private static void ReceiveCallback( IAsyncResult ar ) { try { // Retrieve the state object and the cli
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());
}
}
我假设你正在使用TCP?在这种情况下,
EndReceive
仅在连接关闭时返回0,因此只有当另一方在发送所有数据后关闭连接时,此代码才会起作用。我确信这不是你想要的:)请考虑使用更新的基于任务的异步API——它们更容易使用,特别是在<代码>等待< /代码>。在任何情况下,为什么不使用TcpListener/TcpClient呢?原始套接字甚至比仅仅使用它们更复杂。@Luaan您能分享一个实现了更新的基于任务的异步API的示例代码吗?你能解释一下为什么你想让我试试TcpClient而不是sockets吗。我是新来的。所以一点解释会有帮助。谢谢,我有一些样品,还没有准备好生产,但这应该是一个不错的起点。使用TcpClient而不是sockets的原因很简单—sockets的级别甚至低于TcpClient。TcpClient公开TCP所属的逻辑流,而不是使用一般的发送/接收方法(也用于UDP,它是基于消息的,而不是基于流的)。