一旦你有Receive
东西,你就需要开始另一个Receive
东西,以便从别人那里接收东西。
如果要接收多个连接,通常会使用异步 IO。例如:
var client = new UdpClient(endPoint);
AsyncCallback callback = null;
callback = ar =>
{
IPEndPoint newIncomingEndPoint = endPoint;
byte[] data = client.EndReceive(ar, ref newIncomingEndPoint);
client.BeginReceive(callback, null);
// TODO: do something with data
};
client.BeginReceive(callback, null);
或者,如果您更喜欢不使用匿名方法的东西(来自http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive.aspx):
public static bool messageReceived = false;
public static void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
Byte[] receiveBytes = u.EndReceive(ar, ref e);
string receiveString = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("Received: {0}", receiveString);
messageReceived = true;
}
public static void ReceiveMessages()
{
// Receive a message and write it to the console.
IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
UdpClient u = new UdpClient(e);
UdpState s = new UdpState();
s.e = e;
s.u = u;
Console.WriteLine("listening for messages");
u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
// Do some work while we wait for a message. For this example,
// we'll just sleep
while (!messageReceived)
{
Thread.Sleep(100);
}
}
如果您不使用异步 IO,则在处理现有连接时将无法接收另一个连接Receive
- 因此您有一个巨大的时间差距,想要连接的东西可能会被拒绝。