.Net异步套接字 [英] .Net Asynchronous Socket

查看:86
本文介绍了.Net异步套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.Net套接字异步模型(BeginAccept/EndAccept ...等)开发异步游戏服务器.

我面临的问题是这样描述的:
当我仅连接一个客户端时,服务器响应时间非常快,但是一旦连接了第二个客户端,服务器响应时间就会增加太多.

在两种情况下,我都测量了从客户端向服务器发送消息直到得到回复的时间.我发现一个客户端的平均时间约为17毫秒,而两个客户端的平均时间约为280毫秒!!!
我真正看到的是:当2个客户端连接并且其中只有一个正在移动时(即,从服务器请求服务),这等效于仅连接一个客户端的情况.但是,当2个客户端同时移动时(即同时从服务器请求服务),它们的动作将变得非常慢(就像服务器以顺序(即不同时)答复每个客户端一样).

基本上,我正在做的是:

当客户从服务器请求运动许可并且服务器同意他的请求时,服务器随后将客户的新位置广播给所有玩家.因此,如果两个客户端同时移动,则服务器最终将尝试同时向两个客户端广播每个客户端的新位置.

例如:
-Client1要求转到位置(2,2)
-Client2要求转到位置(5,5)
+服务器发送到每个Client1& Client2的两条消息:
message1:位于(2,2)的Client1"
message2:位于(5,5)处的Client2"

我认为问题来自MSDN文档在这里.

下面是服务器的代码:

I''m developing an Asynchronous Game Server using .Net Socket Asynchronous Model( BeginAccept/EndAccept...etc.)

The problem I''m facing is described like that:
When I have only one client connected the server response time is very fast but once a second client connects, the server response time increases too much.

I''ve measured the time from a client sends a message to the server until it gets the reply in both cases. I found that the average time in case of one client is about 17ms and in case of 2 clients about 280ms!!!

What I really see is that: When 2 clients are connected and only one of them is moving(i.e. requesting service from the server) it is equivalently equal to the case when only one client is connected. However, when the 2 clients move at the same time(i.e. requests service from the server at the same time) their motion becomes very slow (as if the server replies each one of them in order i.e. not simultaneously).

Basically, what I am doing is that:

When a client requests a permission for motion from the server and the server grants him the request, the server then broadcasts the new position of the client to all the players. So if two clients are moving in the same time, the server is eventually trying to broadcast to both clients the new position of each of them at the same time.

EX:
-Client1 asks to go to position (2,2)
-Client2 asks to go to position (5,5)
+Server sends to each of Client1 & Client2 two messages:
message1: "Client1 at (2,2)"
message2: "Client2 at (5,5)"

I believe that the problem comes from the fact that Socket class is thread safe according MSDN documentation here.

Below is the code for the server:

    /// <summary>
    /// This class is responsible for handling packet receiving and sending
    /// </summary>
    public class NetworkManager
    {
 /// <summary>
        /// The <c>portNumber</c> configuration key.
        /// </summary>
        private const string PortNameConfigKey = "portNumber";

        /// <summary>
        /// An integer to hold the server port number to be used for the connections. Its default value is 5000.
        /// </summary>
        private readonly int port = 5000;

        /// <summary>
        /// hashtable contain all the clients connected to the server.
        /// key: player Id
        /// value: socket
        /// </summary>
        private readonly Hashtable connectedClients = new Hashtable();

        /// <summary>
        /// An event to hold the thread to wait for a new client
        /// </summary>
        private readonly ManualResetEvent resetEvent = new ManualResetEvent(false);

        /// <summary>
        /// keeps track of the number of the connected clients
        /// </summary>
        private int clientCount;

        /// <summary>
        /// The socket of the server at which the clients connect
        /// </summary>
        private readonly Socket mainSocket =
            new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        /// <summary>
        /// The socket exception that informs that a client is disconnected
        /// </summary>
        private const int ClientDisconnectedErrorCode = 10054;

        /// <summary>
        /// The only instance of this class. 
        /// </summary>
        private static readonly NetworkManager networkManagerInstance = new NetworkManager();

        /// <summary>
        /// A delegate for the new client connected event.
        /// </summary>
        /// <param name="sender">the sender object</param>
        /// <param name="e">the event args</param>
        public delegate void NewClientConnected(Object sender, SystemEventArgs e);

        /// <summary>
        /// A delegate for the position update message reception.
        /// </summary>
        /// <param name="sender">the sender object</param>
        /// <param name="e">the event args</param>
        public delegate void PositionUpdateMessageRecieved(Object sender, PositionUpdateEventArgs e);

        /// <summary>
        /// A delegate for the attack message reception.
        /// </summary>
        /// <param name="sender">the sender object.</param>
        /// <param name="e">the attack event args.</param>
        public delegate void AttackMessageRecieved(object sender, AttackEventArgs e);

        /// <summary>
        /// A delegate for the client disconnection event.
        /// </summary>
        /// <param name="sender">the sender object.</param>
        /// <param name="e">the client disconnection event args.</param>
        public delegate void ClientDisconnected(object sender, ClientDisconnectedEventArgs e);

        /// <summary>
        /// A delegate for throw exceptions events.
        /// </summary>
        /// <param name="sender">the sender object</param>
        /// <param name="e">the <see cref="DebugEventArgs" /> args.</param>
        public delegate void DebugException(object sender, DebugEventArgs e);

        /// <summary>
        /// The event which fires when a client sends an attack message
        /// </summary>
        public AttackMessageRecieved AttackMessageEvent
        {
            get;
            set;
        }
        /// <summary>
        /// The event which fires when a client sends a position message 
        /// </summary>
        public PositionUpdateMessageRecieved PositionUpdateMessageEvent
        {
            get;
            set;
        }
        /// <summary>
        /// The event which fires on a client disconnection
        /// </summary>
        public ClientDisconnected ClientDisconnectedEvent
        {
            get;
            set;
        }

        /// <summary>
        /// The event that fires when an exception is thrown. Used for testing and debugging only.
        /// </summary>
        public DebugException DebugExceptionEvent
        {
            get;
            set;
        }

        /// <summary>
        /// The event which fires on a client connection start
        /// </summary>
        public NewClientConnected NewClientEvent
        {
            get;
            set;
        }

        /// <summary>
        /// keeps track of the number of the connected clients
        /// </summary>
        public int ClientCount
        {
            get
            {
                return clientCount;
            }
        }

        /// <summary>
        /// A getter for this class instance.
        /// </summary>
        /// <value><see cref="NetworkManager" /> only instance.</value>
        public static NetworkManager NetworkManagerInstance
        {
            get
            {
                return networkManagerInstance;
            }
        }

        /// <summary>
        /// A private constructor to prevent public instantiations from this class.
        /// </summary>
        private NetworkManager()
        {
            string portValue = ConfigurationManager.AppSettings[PortNameConfigKey];
            if (portValue != null)
            {
                try
                {
                    port = Convert.ToInt32(portValue);
                }
                catch
                {
                    throw new ConfigurationErrorsException(
                        string.Format(
                            "Error occurred during reading the configuration file."
                            + " ''{0}'' configuration key is incorrect",
                            PortNameConfigKey));
                }
            }
        }

  /// <summary>
        /// Starts the game server and holds this thread alive
        /// </summary>
        public void StartServer()
        {
            //Bind the mainSocket to the server IP address and port
            mainSocket.Bind(new IPEndPoint(IPAddress.Any, port));

            //The server starts to listen on the binded socket with  max connection queue 1024
            mainSocket.Listen(1024);

            //Start accepting clients asynchronously
            mainSocket.BeginAccept(OnClientConnected, null);

            //Wait until there is a client wants to connect
            resetEvent.WaitOne();
        }
        /// <summary>
        /// Receives connections of new clients and fire the NewClientConnected event
        /// </summary>
        private void OnClientConnected(IAsyncResult asyncResult)
        {
            Interlocked.Increment(ref clientCount);

            ClientInfo newClient = new ClientInfo
                                   {
                                       WorkerSocket = mainSocket.EndAccept(asyncResult),
                                       PlayerId = clientCount
                                   };
            //Add the new client to the hashtable and increment the number of clients
            connectedClients.Add(newClient.PlayerId, newClient);

            //fire the new client event informing that a new client is connected to the server
            if (NewClientEvent != null)
            {
                NewClientEvent(this, System.EventArgs.Empty);
            }

            newClient.WorkerSocket.BeginReceive(newClient.Buffer, 0, BasePacket.GetMaxPacketSize(),
                SocketFlags.None, new AsyncCallback(WaitForData), newClient);

            //Start accepting clients asynchronously again
            mainSocket.BeginAccept(OnClientConnected, null);
        }

 /// <summary>
        /// Waits for the upcoming messages from different clients and fires the proper event according to the packet type.
        /// </summary>
        /// <param name="asyncResult"></param>
        private void WaitForData(IAsyncResult asyncResult)
        {
            ClientInfo sendingClient = null;
            try
            {
                //Take the client information from the asynchronous result resulting from the BeginReceive
                sendingClient = asyncResult.AsyncState as ClientInfo;

                // If client is disconnected, then throw a socket exception
                // with the correct error code.
                if (!IsConnected(sendingClient.WorkerSocket))
                {
                    throw new SocketException(ClientDisconnectedErrorCode);
                }
                //Console.Out.WriteLine(string.Format("Received from Client# {0}. Thread# {1}", sendingClient.PlayerId,
                //    Thread.CurrentThread.ManagedThreadId));
                //End the pending receive request
                sendingClient.WorkerSocket.EndReceive(asyncResult);
                //Fire the appropriate event
                FireMessageTypeEvent(sendingClient.ConvertBytesToPacket() as BasePacket);

                // Begin receiving data from this client
                sendingClient.WorkerSocket.BeginReceive(sendingClient.Buffer, 0, BasePacket.GetMaxPacketSize(),
                    SocketFlags.None, new AsyncCallback(WaitForData), sendingClient);
            }
            catch (SocketException e)
            {
                // if debugging is allowed, then pass the exception.
                if (DebugExceptionEvent != null)
                {
                    DebugExceptionEvent(this, new DebugEventArgs(e));
                }

                if (e.ErrorCode == ClientDisconnectedErrorCode)
                {
                    // Close the socket.
                    if (sendingClient.WorkerSocket != null)
                    {
                        sendingClient.WorkerSocket.Close();
                        sendingClient.WorkerSocket = null;
                    }

                    // Remove it from the hash table.
                    connectedClients.Remove(sendingClient.PlayerId);

                    if (ClientDisconnectedEvent != null)
                    {
                        ClientDisconnectedEvent(this, new ClientDisconnectedEventArgs(sendingClient.PlayerId));
                    }
                }
            }
            catch (Exception e)
            {
                // if debugging is allowed, then pass the exception.
                if (DebugExceptionEvent != null)
                {
                    DebugExceptionEvent(this, new DebugEventArgs(e));
                }

                // Begin receiving data from this client
                sendingClient.WorkerSocket.BeginReceive(sendingClient.Buffer, 0, BasePacket.GetMaxPacketSize(),
                    SocketFlags.None, new AsyncCallback(WaitForData), sendingClient);
            }
        }
        /// <summary>
        /// Broadcasts the input message to all the connected clients
        /// </summary>
        /// <param name="message"></param>
        public void BroadcastMessage(BasePacket message)
        {
            byte[] bytes = message.ConvertToBytes();
            foreach (ClientInfo client in connectedClients.Values)
            {
                client.WorkerSocket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, SendAsync, client);
            }
        }

        /// <summary>
        /// Sends the input message to the client specified by his ID.
        /// </summary>
        ///
        /// <param name="message">The message to be sent.</param>
        /// <param name="id">The id of the client to receive the message.</param>
        public void SendToClient(BasePacket message, int id)
        {

            byte[] bytes = message.ConvertToBytes();
            (connectedClients[id] as ClientInfo).WorkerSocket.BeginSend(bytes, 0, bytes.Length,
                SocketFlags.None, SendAsync, connectedClients[id]);
        }

 private void SendAsync(IAsyncResult asyncResult)
        {
            ClientInfo currentClient = (ClientInfo)asyncResult.AsyncState;
            currentClient.WorkerSocket.EndSend(asyncResult);
        }

 /// <summary>
        /// Fires the event depending on the type of received packet
        /// </summary>
        /// <param name="packet">The received packet.</param>
        void FireMessageTypeEvent(BasePacket packet)
        {

            switch (packet.MessageType)
            {
                case MessageType.PositionUpdateMessage:
                    if (PositionUpdateMessageEvent != null)
                    {
                        PositionUpdateMessageEvent(this, new PositionUpdateEventArgs(packet as PositionUpdatePacket));
                    }
                    break;
            }

        }
}



触发的事件在不同的类中处理,这是PositionUpdateMessage的事件处理代码(其他处理程序无关):



The events fired are handled in a different class, here are the event handling code for the PositionUpdateMessage (Other handlers are irrelevant):

     private readonly Hashtable onlinePlayers = new Hashtable();

     /// <summary>
     /// Constructor that creates a new instance of the GameController class.
     /// </summary>
     private GameController()
     {
         //Start the server
         server = new Thread(networkManager.StartServer);
         server.Start();
         //Create an event handler for the NewClientEvent of networkManager

         networkManager.PositionUpdateMessageEvent += OnPositionUpdateMessageReceived;
     }

     /// <summary>
     /// this event handler is called when a client asks for movement.
     /// </summary>
     private void OnPositionUpdateMessageReceived(object sender, PositionUpdateEventArgs e)
     {
         Point currentLocation = ((PlayerData)onlinePlayers[e.PositionUpdatePacket.PlayerId]).Position;
         Point locationRequested = e.PositionUpdatePacket.Position;


((PlayerData)onlinePlayers[e.PositionUpdatePacket.PlayerId]).Position = locationRequested;

             // Broadcast the new position
             networkManager.BroadcastMessage(new PositionUpdatePacket
                                             {
                                                 Position = locationRequested,
                                                 PlayerId = e.PositionUpdatePacket.PlayerId
                                             });


         }
     }

推荐答案

-禁用的Nagle算法,即set Socket.NoDelay = true
-在WaitForData方法中,将对BeginRecieve的调用移至用于处理先前接收到的数据包
-disabled Nagle Algorithm i.e. set Socket.NoDelay = true
-in WaitForData method, moved call to BeginRecieve befor handling the previously received packet


这篇关于.Net异步套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆