gpt4 book ai didi

c# - C#中的UDPClient

转载 作者:行者123 更新时间:2023-12-04 06:40:21 24 4
gpt4 key购买 nike

我在 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”而不是 recieve。 MSDN有一个例子:

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

关于c# - C#中的UDPClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4333719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com