0

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);
}
chetan rane
  • 533
  • 2
  • 10
  • 25
  • 1
    Actually, the code you included calls `BeginAccept()` right away after handling the completion of the previous `BeginAccept()`, and so should be able to handle multiple connections without any problems. If you disagree with that assessment, please post a good, complete, concise code example demonstrating what you mean. See http://stackoverflow.com/help/mcve – Peter Duniho Nov 18 '14 at 07:53
  • Hi Peter, thanks for your quick reply. I, AcceptCallback, how could i differentiate multiple clients Socket.GetHashCode() is what i was looking for..but msdn said that its not guaranteed to give you unique id i am able to receive the concurrent requests, but unable to maintained the identity of client if they send another request – chetan rane Nov 18 '14 at 09:13
  • 1
    The "identity" of a client is its IP+port. If nothing else, you can use that to distinguish different clients. The accepted `Socket` instance itself is also an identity; i.e., when you call `BeginReceive()` on a `Socket` instance, that receive operation will only be completed for that `Socket` instance, along with whatever user-provided state object value you provide in the call. Typically, then, servers have a "user state" object that contains information specific to each client. In the simple echo-server example, you just reply on the same `Socket` for which the operation just completed. – Peter Duniho Nov 18 '14 at 09:38

1 Answers1

1

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.

Thomas Lielacher
  • 1,037
  • 9
  • 20
  • Hi Thomas, thanks for quick reply. As per my knowledge, using multi-threading is not efficient way, instead async socket is more efficient way. Honestly I am a newbie to socket programming, so not sure about this. – chetan rane Nov 18 '14 at 09:19