2

我在 C# 的 UDPClient 中使用。我调用接收函数,但是当我运行应用程序时。程序进入永恒循环。为什么会出现这种现象?也许是因为这个端口上没有可用的数据?我能做些什么?

我写了以下代码:

       UdpClient udpClient = new UdpClient(623);
        try
        {
            udpClient.Connect("10.0.0.16", 623);

            // Sends a message to the host to which you have connected.
            Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");

            udpClient.Send(sendBytes, sendBytes.Length);

            // Sends a message to a different host using optional hostname and port parameters.
            UdpClient udpClientB = new UdpClient();
            udpClientB.Send(sendBytes, sendBytes.Length, "10.0.0.16", 623);

            //IPEndPoint object will allow us to read datagrams sent from any source.
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

            // Blocks until a message returns on this socket from a remote host.
            Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
            string returnData = Encoding.ASCII.GetString(receiveBytes);

            // Uses the IPEndPoint object to determine which of these two hosts responded.
            Console.WriteLine("This is the message you received " +
                                         returnData.ToString());
            Console.WriteLine("This message was sent from " +
                                        RemoteIpEndPoint.Address.ToString() +
                                        " on their port number " +
                                        RemoteIpEndPoint.Port.ToString());

            udpClient.Close();
            udpClientB.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

谢谢

4

1 回答 1

3

我怀疑这是因为没有数据,但要对此进行测试,您可以尝试实现“BeginRecieve”而不是“recieve”。MSDN 有一个例子:

http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive.aspx

于 2010-12-02T10:34:47.787 回答