C#异步UDP网络,10057错误

时间:2012-02-16 22:38:12

标签: c# networking udp

过去两天我一直试图让这台异步UDP服务器正常工作,现在我正在撞墙。

当我尝试从SocketException中的RemoteEndPoint获取Socket时,我目前正在尝试获得100 ReceiveCallback

在调试器socket查看时,state已填满。 LocalEndPoint通常设为{0.0.0.0:53},但RemoteEndPoint表示投放了SocketException。我不明白我的设置中缺少的是什么。任何帮助,提示,指导欢迎。

namespace UDPServer
{
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;

    public class StateObject
    {
        // Client socket
        public Socket socket = null;

        // Size of the receive buffer
        public const int BufferSize = 1024;

        // Receive buffer
        public byte[] buffer = new byte[BufferSize];
    }

    public class ServerAsync
    {
        private static int portNumber = 53;
        public static ManualResetEvent WaitEvent = new ManualResetEvent(false);

        public static void StartListening()
        {
            // Data buffer
            byte[] bytes = new byte[1024];

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

            Console.WriteLine("Listening for UDP queries on port 53");

            while (true)
            {
                // Set event to non-signaled state.
                WaitEvent.Reset();
                Console.WriteLine("Waiting for a connection...");
                StateObject state = new StateObject();

                state.socket = socket;
                socket.BeginReceiveFrom(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, ref client, new AsyncCallback(ReceiveCallback), state);

                // Wait until a connection is made before continuing.
                WaitEvent.WaitOne();
            }
        }

        public static void ReceiveCallback(IAsyncResult ar)
        {
            // Signal main thread to continue.
            WaitEvent.Set();

            int bytesRead = 0;

            try
            {
                if (ar.IsCompleted)
                {
                    StateObject state = (StateObject)ar.AsyncState;
                    Socket socket = state.socket;

                    IPEndPoint sender = (IPEndPoint)socket.RemoteEndPoint;
                    EndPoint remoteEndPoint = (EndPoint)sender;

                    bytesRead = socket.EndReceiveFrom(ar, ref remoteEndPoint);

                    if (bytesRead > 0)
                    {
                        Console.WriteLine("Received {0} bytes from {1}:{2}: {3}", bytesRead, sender.Address.ToString(), sender.Port.ToString(), BitConverter.ToString(state.buffer));

                        socket.BeginReceiveFrom(state.buffer, 0, StateObject.BufferSize, 0, ref remoteEndPoint, new AsyncCallback(ReceiveCallback), state);
                    }

                }
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException: " + se.ErrorCode + ": " + se.Message);
            }
            catch (ObjectDisposedException ode)
            {
                Console.WriteLine("Socket closed: " + ode.Message);
            }
        }

        public static void Main(string[] args)
        {
            Console.WriteLine("Server starting up...");

            StartListening();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

当EndCallback也开始新的读取时,为什么你的主线程循环并从端口读取?在我看来,两个线程将尝试使用相同的StateObject同时从端口读取。

此外,您的接收回调是使用AsyncResult的缓冲区来启动新的读取操作。返回后,您知道套接字对AsyncResult对象的作用吗?你能确定它没有处理它吗?您可能需要为每个读取请求创建一个新的AsyncResult,以便它们保持真正独立。