0

我偶尔会看到我的 udp 多播接收器两次接收到一个数据包。我设置多播客户端如下:

private static void setupUdpMulticastClient()
    {
        //IPEndPoint ipRXEnd = new IPEndPoint(IPAddress.Any,multicastPort);
        IPEndPoint ipRXEnd = new IPEndPoint(IPAddress.Parse(emulatorIpaddr), multicastPort);
        udpMulticastClient = new UdpClient();
        udpMulticastClient.Client.ExclusiveAddressUse = false;
        udpMulticastClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        udpMulticastClient.Client.Bind(ipRXEnd);
    }

emulatorIpaddr 是一个 192.xxx 地址。

接收器如下所示:

public static void MulticastSetBeginReceive()
    {
        //IPAddress ipSSDP = IPAddress.Parse(multicastIP);
        IPAddress ipSSDP = IPAddress.Parse(emulatorIpaddr);
        IPEndPoint ipRXEnd = new IPEndPoint(ipSSDP, multicastPort);
        UdpState udpListener = new UdpState();
        udpListener.e = ipRXEnd;

        if (udpMulticastClient == null)
        { setupUdpMulticastClient();}

        udpListener.u = udpMulticastClient;
        udpMulticastClient.BeginReceive(new AsyncCallback(MulticastReceiveCallback), udpListener);
    }

似乎偶尔会触发异步回调 2 次。为了完整起见,这里是回调代码:

public static void MulticastReceiveCallback(IAsyncResult ar)
    {
        try
        {
            UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
            IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

            if (u.Client != null)
            {
                Byte[] receiveBytes = u.EndReceive(ar, ref e);
                string receiveString = Encoding.ASCII.GetString(receiveBytes);
                string from = e.ToString();
                string to = ((UdpState)(ar.AsyncState)).e.ToString();
                msgReceiver(DateTime.Now.ToLocalTime(), from, to, receiveString);
            }
            if (running)
                MulticastSetBeginReceive();
        }
        catch (Exception ex)
        {
            log.Debug(ex.Message);
            log.Debug(ex.StackTrace);
        }
    }

我正在运行 Windows 7 和 .Net 4。

是否有人看到代码存在问题,或者知道 .NET 或 win 7 存在问题,这会导致这种行为。

4

1 回答 1

0

对于接收字符串,使用 Encoding.Unicode.GetString(receiveBytes, 0, receiveBytes.Count())

而不是 ASCII

于 2013-05-26T06:15:06.927 回答