[英]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.