繁体   English   中英

C#中的UDPClient

[英]UDPClient in C#

我在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());
        }

谢谢

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM