UDP总是在后台通过LAN监听

时间:2012-09-20 20:17:18

标签: c# udp lan

我正在尝试使用UDP over LAN,正如你在这里看到的那样,我将一个包发送到另一个包,但是当你还在列表时可以发送包,因为当我开始接收进程时停止响应。 我知道这与Threads有关,但我需要一些帮助。 感谢所有的帮助,提前谢谢。

UdpClient client = new UdpClient();

public void SendPacket()
{
    byte[] packet = Encoding.ASCII.GetBytes(DateTime.Now.ToString("HH:mm:ss:ff"));
    client.Send(packet, packet.Length, tbIP.Text, 444);
    dgvSend.Rows.Add(DateTime.Now.ToString("HH:mm:ss:ff"));
}

public void ReceivePacket()
{
    client = new UdpClient(444);
    IPEndPoint server = new IPEndPoint(IPAddress.Any, 0);
    byte[] packet = client.Receive(ref server);
    dgvReceiv.Rows.Add(Encoding.ASCII.GetString(packet), DateTime.Now.ToString("HH:mm:ss:ff"));
}

1 个答案:

答案 0 :(得分:1)

只要你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时无法接收另一个连接 - 因此您可能会在需要连接的内容被拒绝的时候留下巨大的空白。