.Net 3.5异步Socket服务器性能问题

发布于 2024-09-02 10:10:43 字数 10151 浏览 3 评论 0原文

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

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

我测量了两种情况下从客户端向服务器发送消息到得到回复的时间。我发现,1 个客户端的平均时间约为 17 毫秒,2 个客户端的平均时间约为 280 毫秒!

我真正看到的是:当2个客户端连接并且只有其中一个在移动(即向服务器请求服务)时,它等同于只有一个客户端连接时的情况(即快速响应)。然而,当两个客户端同时移动(即同时向服务器请求服务)时,它们的动作会变得非常慢(就好像服务器按顺序回复其中每个客户端一样,即不同时回复)。

基本上,我正在做的是:

当客户端向服务器请求运动许可并且服务器授予他该请求时,服务器会将客户端的新位置广播给所有玩家。因此,如果两个客户端同时移动,服务器最终会尝试同时向两个客户端广播它们各自的新位置。

例如:

  • 客户端 1 要求转到位置 (2,2)
  • 客户端 2 要求转到位置 (5,5)
  • 服务器发送到客户端 1 和客户端 2 中的每一个。 Client2有相同的两条消息:
  • message1: "Client1 at (2,2)"
  • message2: "Client2 at (5,5)"

我相信问题来自于事实上,根据 MSDN 文档,Socket 类是线程安全的 http: //msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx。 (不确定这就是问题)

下面是服务器的代码:

/// 
/// This class is responsible for handling packet receiving and sending
/// 
public class NetworkManager
{
    /// 
    /// An integer to hold the server port number to be used for the connections. Its default value is 5000.
    /// 
    private readonly int port = 5000;

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

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

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

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

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

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

    /// 
    /// A delegate for the new client connected event.
    /// 
    /// the sender object
    /// the event args
    public delegate void NewClientConnected(Object sender, SystemEventArgs e);

    /// 
    /// A delegate for the position update message reception.
    /// 
    /// the sender object
    /// the event args
    public delegate void PositionUpdateMessageRecieved(Object sender, PositionUpdateEventArgs e);

    /// 
    /// The event which fires when a client sends a position message 
    /// 
    public PositionUpdateMessageRecieved PositionUpdateMessageEvent
    {
        get;
        set;
    }

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

    /// 
    /// A getter for this class instance.
    /// 
    ///  only instance.
    public static NetworkManager NetworkManagerInstance
    {
        get
        {
            return networkManagerInstance;
        }
    }

    private NetworkManager()
    {}

    /// Starts the game server and holds this thread alive
    /// 
    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();
    }
    /// 
    /// Receives connections of new clients and fire the NewClientConnected event
    /// 
    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);
    }

    /// Waits for the upcoming messages from different clients and fires the proper event according to the packet type.
    /// 
    /// 
    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);
            }

            //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 (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)
        {
            // Begin receiving data from this client
            sendingClient.WorkerSocket.BeginReceive(sendingClient.Buffer, 0, BasePacket.GetMaxPacketSize(),
                SocketFlags.None, new AsyncCallback(WaitForData), sendingClient);
        }
    }
    /// 
    /// Broadcasts the input message to all the connected clients
    /// 
    /// 
    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);
        }
    }

    /// 
    /// Sends the input message to the client specified by his ID.
    /// 
    ///
    /// The message to be sent.
    /// The id of the client to receive the message.
    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);
    }

    /// Fires the event depending on the type of received packet
    /// 
    /// The received packet.
    void FireMessageTypeEvent(BasePacket packet)
    {

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

    }
}

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

    private readonly Hashtable onlinePlayers = new Hashtable();

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

        networkManager.PositionUpdateMessageEvent += OnPositionUpdateMessageReceived;
    }

    /// 
    /// this event handler is called when a client asks for movement.
    /// 
    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
                                            });


        }

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(i.e. fast response). 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 the same 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 http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx. (NOT SURE THAT IT IS THE PROBLEM)

Below is the code for the server:

/// 
/// This class is responsible for handling packet receiving and sending
/// 
public class NetworkManager
{
    /// 
    /// An integer to hold the server port number to be used for the connections. Its default value is 5000.
    /// 
    private readonly int port = 5000;

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

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

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

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

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

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

    /// 
    /// A delegate for the new client connected event.
    /// 
    /// the sender object
    /// the event args
    public delegate void NewClientConnected(Object sender, SystemEventArgs e);

    /// 
    /// A delegate for the position update message reception.
    /// 
    /// the sender object
    /// the event args
    public delegate void PositionUpdateMessageRecieved(Object sender, PositionUpdateEventArgs e);

    /// 
    /// The event which fires when a client sends a position message 
    /// 
    public PositionUpdateMessageRecieved PositionUpdateMessageEvent
    {
        get;
        set;
    }

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

    /// 
    /// A getter for this class instance.
    /// 
    ///  only instance.
    public static NetworkManager NetworkManagerInstance
    {
        get
        {
            return networkManagerInstance;
        }
    }

    private NetworkManager()
    {}

    /// Starts the game server and holds this thread alive
    /// 
    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();
    }
    /// 
    /// Receives connections of new clients and fire the NewClientConnected event
    /// 
    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);
    }

    /// Waits for the upcoming messages from different clients and fires the proper event according to the packet type.
    /// 
    /// 
    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);
            }

            //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 (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)
        {
            // Begin receiving data from this client
            sendingClient.WorkerSocket.BeginReceive(sendingClient.Buffer, 0, BasePacket.GetMaxPacketSize(),
                SocketFlags.None, new AsyncCallback(WaitForData), sendingClient);
        }
    }
    /// 
    /// Broadcasts the input message to all the connected clients
    /// 
    /// 
    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);
        }
    }

    /// 
    /// Sends the input message to the client specified by his ID.
    /// 
    ///
    /// The message to be sent.
    /// The id of the client to receive the message.
    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);
    }

    /// Fires the event depending on the type of received packet
    /// 
    /// The received packet.
    void FireMessageTypeEvent(BasePacket packet)
    {

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

    }
}

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();

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

        networkManager.PositionUpdateMessageEvent += OnPositionUpdateMessageReceived;
    }

    /// 
    /// this event handler is called when a client asks for movement.
    /// 
    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
                                            });


        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故事灯 2024-09-09 10:10:43

您应该移动

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

到该行之后,

ClientInfo newClient = new ClientInfo  

这样您就不会阻止接受新连接的时间超过必要的时间。

相信问题出在
事实上 Socket 类是线程
安全

这应该与您的场景无关。

您是否记得在套接字上设置 NoDelay 属性以禁用 Nagling?

You should move

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

To right after the line

ClientInfo newClient = new ClientInfo  

So that you don't block on accepting new connections longer than necessary.

believe that the problem comes from
the fact that Socket class is thread
safe

That shouldn't be relevant for your scenario.

Did you remember to set the NoDelay property on your socket to disable Nagling?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文