UDP套接字侦听器未接收数据

时间:2015-03-30 13:52:58

标签: c# .net sockets udp udpclient

我的本​​地IP是:192.168.0.70, 外部IP是:192.168.0.50:60000

我想从外部ip发送到本地ip接收数据。我使用Socket类,因为我可以使用远程IPEndPoint发送数据。但是当Udp连接关闭时,本地ip的端口动态变化。我怎样才能收到数据?

private static void UdpConnect()
    {
        try
        {
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("192.168.0.50"), 60000);

            Socket client = new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram, ProtocolType.Udp);
            client.Connect(remoteEP);

            byte[] sendbuffer = { 1, 2, 3 };

            client.Send(sendbuffer);

            byte[] receivebuffer = new byte[512];

            client.Receive(receivebuffer);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

1 个答案:

答案 0 :(得分:1)

如果需要侦听特定的本地端口,请使用Socket.Bind,然后使用Socket.ReceiveFrom。 您不需要Socket.Connect调用,因为UDP是无连接协议。