我在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());
}
谢谢
1 回答
我怀疑这是因为没有数据,但为了测试这个,你可以尝试实现'BeginRecieve'而不是接收 . MSDN有一个例子:
http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive.aspx