.NET UDP多播接收

时间:2013-04-22 14:25:08

标签: .net c#-4.0 udpclient

我偶尔会看到我的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.x.x.x地址。

接收器如下所示:

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的问题会导致此类行为。

1 个答案:

答案 0 :(得分:0)

对于receivetring,请使用 Encoding.Unicode.GetString(receiveBytes,0,receiveBytes.Count())

而不是ASCII