为什么UDPclient组播不工作

本文关键字:工作 UDPclient 为什么 | 更新日期: 2023-09-27 18:12:03

public void send_multicast(string message)
    {
        UdpClient c = new UdpClient(10102);
        Byte[] sendBytes = Encoding.ASCII.GetBytes(message); 
        IPAddress m_GrpAddr = IPAddress.Parse("224.0.0.1");
        IPEndPoint ep = new IPEndPoint(m_GrpAddr,10102);   
        c.MulticastLoopback=true;
         c.JoinMulticastGroup(m_GrpAddr);
        c.Send(sendBytes,sendBytes.Length,ep);
        Console.WriteLine(message);
    }
    public string recv_multicast()
    {
        Console.WriteLine("was here");
        String strData = "";
        //String Ret = "";
        ASCIIEncoding ASCII = new ASCIIEncoding();
        UdpClient c = new UdpClient(10101);
        // Establish the communication endpoint.
        IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 10101);
         IPAddress m_GrpAddr = IPAddress.Parse("224.0.0.1");
         c.JoinMulticastGroup(m_GrpAddr);
            Byte[] data = c.Receive(ref endpoint);
            strData = ASCII.GetString(data);
            //Ret += strData + "'n";
        return strData;
    }

端口有什么问题吗?

recv方法被阻塞,但没有收到消息?

在wireshark中,我可以看到从本地地址端口10102到224.0.0.1 dest_port 0的消息,但是recv没有从组播地址获得msg。

顺便说一句,我在同一台计算机上运行两个实例。参考:http://msdn.microsoft.com/en-us/library/ekd1t784.aspx

**得到解决方案:在send例程

IPEndPoint ep = new IPEndPoint(m_GrpAddr,10102); 
应该

IPEndPoint ep = new IPEndPoint(m_GrpAddr,10101);

接收端口**

为什么UDPclient组播不工作

为了接收自己发送的数据包,需要启用组播环回。

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

您应该在服务器端和客户端同时使用JoinMulticastGroup。如果失败,您也可以尝试使用Wireshark (google一下)来查看数据包是否真的发送了。