1

我正在尝试通过 LAN 使用 UDP,正如您在此处看到的那样,我将一个包与一台 pc 发送到另一台,但是是否可以在您仍在列表时发送数据包,因为当我开始接收时进程停止响应。我知道这与线程有关,但我需要一点帮助。感谢所有帮助,在此先感谢。

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"));
}
4

1 回答 1

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- 因此您有一个巨大的时间差距,想要连接的东西可能会被拒绝。

于 2012-09-20T20:21:52.590 回答