您可以对每个套接字连接进行异步接收并解码来自其他机器的数据以执行您的任务(您可以在此处找到有关异步方法的一些有用信息:http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx)。
要创建连接,您可以:
Socket sock = Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(new IPEndPoint(address, port));
同样,您可以创建多个连接并将引用保存在字典列表中(无论您喜欢哪个)。
要在套接字上异步接收数据,您可以这样做:
sock.BeginReceive(buffer, 0, buffer.len, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
接收操作完成时会调用方法OnDataReceived。
在OnDataReceived 方法中你必须这样做:
void OnDataReceived(IAsyncResult result)
{
int dataReceived = sock.EndReceive(result);
//Make sure that dataReceived is equal to amount of data you wanted to receive. If it is
//less then the data you wanted, you can do synchronous receive to read remaining data.
//When all of the data is recieved, call BeginReceive again to receive more data
//... Do your decoding and call the method ...//
}
希望对你有帮助。