繁体   English   中英

多个客户端的C#.NET UDP套接字异步

[英]C# .NET UDP Sockets Async for Multiple Clients

我一直在环顾四周,但我找不到真正需要的东西,特别是对于UDP。

我正在尝试使基本的syslog服务器在端口514(UDP)上侦听。

我一直在遵循Microsoft在MSDN上的指南: https : //msdn.microsoft.com/zh-cn/library/system.net.sockets.udpclient.beginreceive(v= vs.110) .aspx

它没有明确说明(或者我是盲目的)如何重新打开连接以接收更多数据包。

这是我的代码(与链接基本相同)

     static void Main(string[] args)
    {
        try
        {
            ReceiveMessages();

            Console.ReadLine();

        }catch(SocketException ex)
        {
            if(ex.SocketErrorCode.ToString() == "AddressAlreadyInUse")
            {
                MessageBox.Show("Port already in use!");
            }
        }

    }

    public static void ReceiveMessages()
    {
        // Receive a message and write it to the console.



        UdpState s = new UdpState();

        Console.WriteLine("listening for messages");
        s.u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
        RecieveMoreMessages(s);
    }

    public static void RecieveMoreMessages(UdpState s)
    {
        s.u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
    }

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

        Byte[] receiveBytes = u.EndReceive(ar, ref e);
        string receiveString = Encoding.ASCII.GetString(receiveBytes);

        Console.WriteLine("Received: {0}", receiveString);
    }

我尝试了重复,但是在2次事务之后,我从套接字遇到“缓冲区空间用完”错误。

有任何想法吗?

如果您坚持使用过时的APM模式,则需要在下一个BeginReceive调用中使ReceiveCallback发出。

由于UDP是无连接的,异步IO似乎毫无意义。 可能您应该只使用一个同步接收循环:

while (true) {
 client.Receive(...);
 ProcessReceivedData();
}

删除所有异步代码。

如果您坚持异步IO,请至少使用ReceiveAsync

msdn代码具有消除的睡眠。 您不需要睡眠,但是您需要一个障碍。 尝试这些更改

       public static void ReceiveMessages()
        {
            // Receive a message and write it to the console.



            UdpState s = new UdpState();

            Console.WriteLine("listening for messages");
            s.u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
            //block
            while (true) ;
        }

        public static void RecieveMoreMessages(UdpState s)
        {
            s.u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
        }

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

            Byte[] receiveBytes = u.EndReceive(ar, ref e);
            string receiveString = Encoding.ASCII.GetString(receiveBytes);

            Console.WriteLine("Received: {0}", receiveString);
            RecieveMoreMessages(ar.AsyncState);
        }​

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM