1

我无法接收我自己通过多播发送的数据包。我创建了两个 Udpclient 接收器用于接收多播组上的数据包,发送器用于发送数据包。我的数据包已发送到该组,但我无法收到我发送的数据包....

public void Join()
    {           
            IPAddress ip1 = IPAddress.Any;
            localep = new IPEndPoint(ip1, port);

            Receiver = new UdpClient();
            Receiver.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            Receiver.Client.Bind(localep);

            Sender = new UdpClient();
            Sender.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            Sender.Client.Bind(localep);

            IPAddress ip = IPAddress.Parse(IP);
            remoteep = new IPEndPoint(ip, port);


            Sender.JoinMulticastGroup(ip);
            Sender.EnableBroadcast = true;
            Sender.MulticastLoopback = true;

            Receiver.JoinMulticastGroup(ip);
            Receiver.EnableBroadcast = true;
            Receiver.MulticastLoopback = true;

            udpState.ipEndpt = RemoteIpEndPoint;
            udpState.udpClient = Receiver;

            Receiver.BeginReceive(new AsyncCallback(GetMsg), udpState);             

    }   



void GetMsg(IAsyncResult ar)
{


UdpClient udpClient = (UdpClient)((UdpState)(ar.AsyncState)).udpClient;
            IPEndPoint ipEndpt = (IPEndPoint)((UdpState)(ar.AsyncState)).ipEndpt;
            RecByte = Receiver.EndReceive(ar, ref ipEndpt);
}
//Sending packets logic

McastOTS.Sender.Send(sendBytes, sendBytes.Length, McastOTS.remoteep);
4

1 回答 1

0

在我看来,您需要做的就是在 EndReceive 之后再次调用 BeginReceive。否则,您只会收到 1 条消息,而不会看到任何其他消息...

void GetMsg(IAsyncResult ar)
{
   UdpClient udpClient = (UdpClient)((UdpState)(ar.AsyncState)).udpClient;
   IPEndPoint ipEndpt = (IPEndPoint)((UdpState)(ar.AsyncState)).ipEndpt;
   RecByte = Receiver.EndReceive(ar, ref ipEndpt);
   Receiver.BeginReceive(GetMsg, udpState);
}
于 2013-01-02T20:43:34.583 回答