我正在尝试为无线网状网络创建一个程序(除了名称之外的所有内容)。大多数网络将处理 TCP 消息传递,但要确定所有邻居 IP(因为它们在启动时将是未知的),我选择使用 UDP 广播作为初始发现消息。在大多数情况下,该代码是无关紧要的,因为初始测试似乎有效,目前我不调用它。
以下是接收和注册邻居IP的部分。
protected override void ReceiveMessageUDP()
{
while (live)
{
try
{
UdpListener = new UdpClient(_PORTRECEIVE);
UdpListener.EnableBroadcast = true;
Socket socket = UdpListener.Client;
IPEndPoint endPoint1 = new IPEndPoint(IPAddress.Loopback, _PORTRECEIVE);
IPEndPoint endPoint2 = new IPEndPoint(IPAddress.Any, _PORTRECEIVE);
socket.Bind(endPoint2);
socket.Listen(25);
Socket connected = socket.Accept();
byte[] buffer = new byte[1024];
int length = connected.Receive(buffer);
IPAddress remoteIP = ((IPEndPoint)connected.RemoteEndPoint).Address;
if (!ipAddresses.Contains(remoteIP))
ipAddresses.Add(remoteIP);
Message.Add(Encoding.ASCII.GetString(buffer, 0, length));
}
catch (SocketException e) { Console.WriteLine(e.ErrorCode); }
catch (Exception) { }
}
}
我已经使用两个 IPEndPoints 进行了测试,无论我如何设置它,绑定都会失败,并出现 SocketException.ErrorCode 10022 Windows Socket Error Codes。这是一个无效的参数,但我对这意味着什么感到困惑,因为所需的参数是一个端点。
这在第一次运行时失败,所以它不像我试图重新绑定端口。