套接字服务器,用于同时处理多个客户端请求

本文关键字:客户端 请求 处理 服务器 用于 套接字 | 更新日期: 2023-09-27 18:30:58

我想使用套接字服务器并发处理多个客户端的请求。我有 10 个客户端,可以同时向我的服务器发送请求。我该如何处理?可能吗?

使用以下代码,我一次只能处理一个请求,请求完成后,服务器接受下一个请求。由于第 10 个客户端需要等到 9 个请求完成。

任何帮助将不胜感激

以下是我用于服务器套接字的代码

Socket _serverSocket;
byte[] _buffer = new byte[255];
void SetupServer()
{
    try 
    {
        Console.WriteLine ("Setting up server...");
        IPEndPoint ipEndPoint = new IPEndPoint (IPAddress.Parse(_ip), _port);
        // create server socket to listen new client's connection
        _serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        _serverSocket.Bind (ipEndPoint);
        _serverSocket.Listen (100);
        _serverSocket.BeginAccept (new AsyncCallback (AcceptCallback), null);
    } 
    catch (System.Exception ex) 
    {
        Console.WriteLine ("Server failed :: {0}", ex.Message);
    }
}
void AcceptCallback(IAsyncResult ar)
{
    Socket clientSocket = _serverSocket.EndAccept(ar);
    _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
    clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), clientSocket);
}
void RecieveCallback(IAsyncResult ar)
{
    Socket clientSocket = (Socket)ar.AsyncState;
    int received = clientSocket.EndReceive(ar);
    // check if client is disconnected?
    if (received == 0)
    {
        Console.WriteLine("client is disconnected...");
        return;
    }
    // do whatever you want with received data here...
    byte[] dataBuf = new byte[received];
    Array.Copy(_buffer, dataBuf, received);
    string text = Encoding.ASCII.GetString(dataBuf);
    Console.WriteLine("Received Data: {0}", text);
    // accept new request
    clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), clientSocket);
}

套接字服务器,用于同时处理多个客户端请求

您应该熟悉"多线程服务器"的概念。您应该为每个连接到服务器的客户端启动一个线程。因此,您可以同时处理多个客户端。或者,如果要尝试较新的 .NET 功能,可以使用Tasks Parallel Library

但是网络上有很多例子描述了如何实现这样的服务器。