Socket Server to handle multiple clients request concurrently

2.3k views Asked by At

I want to handle multiple client's request concurrently using Socket Server. i have 10 clients, which can send request to my server at same time. How could i handle this? Is it possible?

With below code, i can handle only one request at a time, after completion of the request, server accepts next request. Due to this 10th client need to wait until 9 requests get complete.

Any help would be appreciated

Below is the code i am using for Server Socket

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);
}
1

There are 1 answers

1
Thomas Lielacher On

You should familiarize yourself with the concept of a "multi threaded server". You should start a thread for each client which connects to the server. So you can simultaneously handle multiple clients. Or you could use Tasks Parallel Library if you want to try newer .NET features.

But there are many examples out there in the web that describe how to implement such a server.