概述:我已经设置了一个服务器和一个客户端,两者都尝试使用 UDP 发现彼此。当服务器启动时,它会发送一条多播消息 (239.1.1.1),表明它还活着。当客户端启动时,它会发送一条多播消息 (239.1.1.2),表明它是活动的。服务器和客户端都订阅了彼此的多播消息以接收它们的传输。这样,无论哪个应用程序(服务器或客户端)首先启动,都会通知其中一个或另一个它们的存在。
在客户端,我执行以下操作:
- 设置一个监听套接字来订阅和接收来自服务器的多播消息。
根据下面的 #3设置接收套接字以接收服务器对客户端多播消息的响应。- 发送客户端正在运行的多播消息(供服务器接收和响应)。
- 接收服务器对 #3 中发送的客户端多播消息的响应。
问题:一切正常,除了两个接收套接字最终都得到服务器(非多播)对客户端的响应。我不清楚这是否是预期的行为。我可以将两个接收插座减少到一个吗?#1 订阅了服务器的多播,而#2 只是在同一端口上侦听来自服务器的直接传输(来自服务器的非多播消息)。我可以安全地移除第二个接收插座吗?
请参阅下面的源代码(为了更简单的代码演示,我删除了异常处理)。
客户端代码:
// 1. Set up a socket and asynchronously listen for server startup multicasts.
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
listenSocket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);
listenSocket.Bind(new IPEndPoint(IPAddress.Any, 50000));
listenSocket.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse("239.1.1.1")));
EndPoint clientEndPoint = new IPEndPoint(0, 0);
listenSocket.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length,
SocketFlags.None, ref clientEndPoint,
new AsyncCallback(OnServerMessageReceived), (object)this);
// 2. Set up socket to receive the server's response to client's multicast.
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
receiveSocket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);
receiveSocket.Bind(new IPEndPoint(IPAddress.Any, 50000));
receiveSocket.ReceiveTimeout = 3000; // Timeout after 3 seconds.
// 3. Send a multicast message for server to respond to.
Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
EndPoint multicastEndPoint = new IPEndPoint(IPAddress.Parse("239.1.1.2"), 50000);
sendSocket.SendTo(packet, packet.Length, SocketFlags.None, multicastEndPoint);
// 4. Wait for server to respond to the multicast message (timeout = 3 seconds).
byte[] receiveBuff = new byte[2048];
EndPoint serverEndPoint = new IPEndPoint(0, 0);
int bytesRead = receiveSocket.ReceiveFrom(receiveBuff, ref serverEndPoint);
服务器代码:
// Receive multicast message sent from client (in asynchronous callback method).
EndPoint clientEndPoint = new IPEndPoint(0, 0);
int bytesRead = listenSocket.EndReceiveFrom(asyncResult, ref clientEndPoint);
// Send response back to the client (change port to 50000).
EndPoint destination = new IPEndPoint((clientEndPoint as IPEndPoint).Address,
50000);
Socket responseSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
responseSocket.SendTo(response, response.Length, SocketFlags.None, destination);