UDP侦听器服务器无法捕获传入数据

时间:2017-03-06 23:37:43

标签: c# sockets networking udp

  • 我有一台IP X.X.X.X的设备不一样 网络作为我的UDP服务器。

  • 此设备与IP X.X.X.X正在发送带有UDP协议的数据包 我的UDP服务器。

  • 将数据包发送到我的UDP服务器的端口5000

  • WireShark显示我的电脑正在接收来自设备的数据包。

    2711    351.573764  X.X.X.X  10.0.0.4   UDP 83    57514 → 5000   Len=61
    
  • 我想捕获已发送的数据包以进行处理。

  • 以下代码来自此example目前,当程序点击 Socket.BeginReceiveFrom 时,控制台应用程序将关闭。

我相信我错过了一些非常基本的东西,但我现在无法看到它,所以欢迎任何东西,提示或建议。

    static private Socket Socket;
    static private byte[] Buffer = new byte[1024];

    static void Main(string[] args)
    {
        StartServer();
    }

    static public void StartServer()
    {
        //Setup the socket and message buffer
        Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        Socket.Bind(new IPEndPoint(IPAddress.Any, 5000));

        //Start listening for a new message.
        EndPoint ClientEndPoint = new IPEndPoint(IPAddress.Any, 5000);
        Socket.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref ClientEndPoint, Receiver, Socket);
    }

    static private void Receiver(IAsyncResult iar)
    {
        //Get the received message.
        Socket ReceiveSocket = (Socket)iar.AsyncState;
        EndPoint ClientEndPoint = new IPEndPoint(IPAddress.Any, 5000);
        int MessageLength = ReceiveSocket.EndReceiveFrom(iar, ref ClientEndPoint);
        byte[] localMsg = new byte[MessageLength];
        Array.Copy(Buffer, localMsg, MessageLength);

        //Start listening for a new message.
        EndPoint NewClientEndPoint = new IPEndPoint(IPAddress.Any, 5000);
        Socket.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref NewClientEndPoint, Receiver, Socket);

        // Do something here
    }

0 个答案:

没有答案