开发者

UDPClient in C#

i use in UDPClient in c#. i invoke the receive function, but the when i am running the app. the program enter to eternity loop. Why is this phenomenon? Maybe because no data were available on this port? what can i do?

I write the following code:

       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 开发者_JS百科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());
        }

thanks


I suspect it's because of no data, but to test this, you could try implementing 'BeginRecieve' instead of recieve. MSDN has an example:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜