过去曾试图单独解决这个问题我甚至都不知道,但谷歌搜索不会对我有所帮助,我需要一些建议。我每隔10秒从本地网络上的另一台PC接收UDP数据包,可以在wireshark中看到它们,但应用程序卡在udpClient.Receive()行上。组播组和端口是正确的值,在main()中检查n + 1次。如果您有任何可能有用的想法,请提出建议解决方案。感谢。
(我试图接收服务器的信息,以便应用程序可以自动开始通过TCP进行通信)
class MulticastListener {
private UdpClient udpClient;
private IPEndPoint remoteEndPoint;
IPAddress multicastIP;
private int port;
public MulticastListener(ref IPAddress multicastIP, int port) {
remoteEndPoint = new IPEndPoint(IPAddress.Any, port);
this.multicastIP = multicastIP;
this.port = port;
udpClient = new UdpClient();
udpClient.Client.Bind(remoteEndPoint);
}
public IPEndPoint GetServer() {
try {
udpClient.JoinMulticastGroup(multicastIP);
} catch (ObjectDisposedException e) {
Console.WriteLine("ERROR: The underlying socket has been closed!");
} catch (SocketException e) {
Console.WriteLine("ERROR: An error occurred when accessing the socket!");
} catch (ArgumentException e) {
Console.WriteLine("ERROR: The IP address is not compatible with the AddressFamily value that defines the addressing scheme of the socket!");
}
Byte[] serverInfoBytes = udpClient.Receive(ref remoteEndPoint);
Stream stream = new MemoryStream(serverInfoBytes); //receives a serialised IPEndpoint object
BinaryFormatter formatter = new BinaryFormatter();
udpClient.Close();
return (IPEndPoint)formatter.Deserialize(stream);
}
}
答案 0 :(得分:0)
正如我评论的那样,您的代码可以100%正常使用。我会检查你发送的是你收到的同一个子网。也许您的发件人未配置到正确的界面?
尝试不同的发件人可能会有所帮助,这是我以前测试的内容:
static void Main(string[] args)
{
//Configuration
var interfaceIp = IPAddress.Parse("192.168.9.121");
var interfaceEndPoint = new IPEndPoint(interfaceIp, 60001);
var multicastIp = IPAddress.Parse("230.230.230.230");
var multicastEndPoint = new IPEndPoint(multicastIp, 60001);
//initialize the socket
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.ExclusiveAddressUse = false;
socket.MulticastLoopback = false;
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
MulticastOption option = new MulticastOption(multicastEndPoint.Address, interfaceIp);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, option);
//bind on a network interface
socket.Bind(interfaceEndPoint);
//initialize args for sending packet on the multicast channel
var sockArgs = new SocketAsyncEventArgs();
sockArgs.RemoteEndPoint = multicastEndPoint;
sockArgs.SetBuffer(new byte[1234], 0, 1234);
//send an empty packet of size 1234 every 3 seconds
while (true)
{
socket.SendToAsync(sockArgs);
Thread.Sleep(3000);
}
}