问题
How can I create a UDP Socket which receives data in local endpoint (I do not know the remote port where the data come from) in a non-blocking way? I use .Net Core in Linux and I thought I could use ReceiveAsync() but it seems to not work this way.
Any suggestions could be useful.
回答1:
I solved this, this way:
    static void Main()
    {
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 0);
        socket.Bind(localEP);
        while( my_condition){
             Receive();}
    }
    private bool Receive()
    {
        received = false;
        if (socket != null)
        {
            SocketAsyncEventArgs ae = new SocketAsyncEventArgs();
            ae.SetBuffer(recvBuffer, 0, recvBuffer.Length);
            // callback
            EventHandler<SocketAsyncEventArgs> rcb = new EventHandler<SocketAsyncEventArgs>(ReceiveCallback);
            ae.Completed += rcb;
            socket.ReceiveAsync(ae);
            int counter = 0;
            int recv_timeout = 500;
            // create a delay waiting for data
            while (!received && counter <= recv_timeout)
            {
                double nanosecs = recv_timeout * 1000;
                long nanosperTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
                int ticks = (int)(nanosecs / nanosperTick);
                Stopwatch sw = Stopwatch.StartNew();
                while (sw.ElapsedTicks < ticks) { }
                sw.Stop();
                counter++;
            }
            ae.Completed -= rcb;
            ae.Dispose();
        }
        return received;
    }
    private void ReceiveCallback(object sender, SocketAsyncEventArgs e)
    {
        switch (e.LastOperation)
        {
            case SocketAsyncOperation.Receive:
                if (e.BytesTransferred == Number_of_bytes_I_wait_for)
                {
                    //get e.Buffer !
                }
                else
                    Console.WriteLine("??? number_of_bytes received: " + e.BytesTransferred);
                break;
        }
    }
回答2:
Since .NET Core v2.1 there is the UnixDomainSocketEndPoint class that can be used for this purpose (documentation). It's also part of .NET standard 2.1.
来源:https://stackoverflow.com/questions/41270620/create-udp-socket-with-net-core