我尝试使用UWP发送和接收UDP多播地址。它在前几次完美运行,但经过一段时间的发送 - 接收过程,它将锁定接收部分。我从异步方法变为同步方法但仍然相同。即使我实例化新的UDP客户端,端口也会被阻止,直到应用程序重新启动。我做错了什么?
private UdpClient udp;
//inside main function:
if (udp == null)
{
udp = new UdpClient(new IPEndPoint(IPAddress.Any, portNumber));
//^the second time this is called, it will complain about port reuse
udp.Client.ReceiveTimeout = udp.Client.SendTimeout = 3000;
//udp.Client.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.ReuseAddress, true);
//^invalid
}
//await udp.SendAsync(data, data.Length, , portNumber);
//I changed from async to synchronous in case it was the issue, but no.
udp.Client.SendTo(data, new IPEndPoint(IPAddress.Parse(ipString), portNumber));
//the receive used to be async, too
byte[] receivedByte = new byte[udp.Client.ReceiveBufferSize];
try
{
udp.Client.Receive(receivedByte);
}
catch (Exception ex)
{
udp.Client.Shutdown(SocketShutdown.Both);
udp = null; // added these, but port still blocked until restart
}
我使用的是UWP,类库中有方法不在这里。
答案 0 :(得分:1)
将UdpClient放入using()语句而不是将其声明为私有字段,并通过将其放入短异步方法来限制其范围后,我不再遇到这些问题了。