你是服务员吗?
如果你是服务器,你会监听一个套接字连接,然后接受这个套接字连接并存储它。然后,您将BeginReceive
使用存储的套接字进行调用。在该BeginReceive
方法中,您将提供一个回调函数来接收和处理数据。
一旦你收到数据,回调就会发生。回调函数将调用EndReceive
存储的连接。这是您获取/处理数据的地方。您还将BeginReceive
再次调用以等待更多数据。
这样,BeginReceive
andEndReceive
就会循环运行:你总是在接收数据,并等待更多的数据。
这是一个例子:
void WaitForData(SocketState state)
{
try
{
state.Socket.BeginReceive(state.DataBuffer, 0, state.DataBuffer.Length, SocketFlags.None, new AsyncCallback(ReadDataCallback), state);
}
catch (SocketException se)
{
//Socket has been closed
//Close/dispose of socket
}
}
public void ReadDataCallback(IAsyncResult ar)
{
SocketState state = (SocketState)ar.AsyncState;
try
{
// Read data from the client socket.
int iRx = state.Socket.EndReceive(ar);
//Handle Data....
WaitForData(state);
}
catch (ObjectDisposedException)
{
//Socket has been closed
//Close/dispose of socket
}
catch (SocketException)
{
//Socket exception
//Close/dispose of socket
}
}
编辑:根据您的评论,这是一个 C# 异步客户端的示例:http: //msdn.microsoft.com/en-us/library/bbx2eya8.aspx。
BeginReceive
/的EndReceive
工作类似于服务器。