从UDP套接字接收Async

时间:2016-12-21 14:10:02

标签: .net linux sockets udp core

我想创建一个UDP套接字来从Local Endpoint接收数据。

我不知道数据来自哪个远程端口,这就是为什么我认为我会使用ReceiveAsync。但它不起作用。

我现在提供我的代码,任何建议都会有用:

public class Program
{
    ManualResetEvent clientDone;
    Socket socket;
    public static void Main(string[] args)
    {
        clientDone = new ManualResetEvent(false);

        socket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPEndPoint localIPEP = new IPEndPoint( IPAddress.Any, 0);
        socket.Bind( (EndPoint) localIPEP);

        while (listening)
            Receive();
    }

    string Receive()
    {
        string response;
        byte[] recvData = new byte[24];

        if (socket != null)
        {
            SocketAsyncEventArgs ae = new SocketAsyncEventArgs();
            ae.SetBuffer(recvData, 0, recvData.Length);

            // callback
            ae.Completed += new EventHandler<SocketAsyncEventArgs>(delegate (object s, SocketAsyncEventArgs e)
            {
                if (e.SocketError == SocketError.Success)
                {
                    response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
                    response.Trim('\0');
                }
                else
                {
                    response = e.SocketError.ToString();
                }

                switch (e.LastOperation)
                {
                    case SocketAsyncOperation.Receive:
                        ProcessReceivedData(e);
                        break;
                }

                clientDone.Set();
            });

            clientDone.Reset();
            Console.WriteLine("Local EndPoint: " + ((IPEndPoint)socket.LocalEndPoint).ToString());
            socket.ReceiveAsync(ae);
            clientDone.WaitOne(1000);
        }

        return response;
    }
}

P.S。我在Linux .Net Core上工作

0 个答案:

没有答案