首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#中的UDPClient

C#中的UDPClient
EN

Stack Overflow用户
提问于 2010-12-02 18:07:00
回答 1查看 1.9K关注 0票数 2

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

我写了以下代码:

代码语言:javascript
复制
       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());
        }

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-12-02 18:34:48

我怀疑这是因为没有数据,但为了测试这一点,你可以尝试实现'BeginRecieve‘而不是recieve。MSDN有一个例子:

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4333719

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档