My question is about asynchronous Client/Server. What I want to achieve is multiple connections working on the server at same time assuming each of them is sending/receiving a few messages and they have to do long-lasting jobs (to transfer a file from the client to the server and vice versa) which is going to take like 5-10 seconds. Currently, my server code below sends one message and reads one message sent by the client and after that there is a Thread.Sleep(5000) knowing that on that place will be my long-lasting operation which is going to take a few seconds to complete.

The problem is that when I open the client, it executes a few connects (usually 12, probably because I have i7-8750H - 12 threads) at same time and the rest are executed separately one by one. You can see that on the GIF below. The problem is that the server takes 12 connects when the client first connects and then each of the connections are done one by one, I tested this by closing the server while leaving client opened and then restarting the server.

How can I make all connections connect and do their long-lasting jobs at same time? I understand that I cannot run more than 12 threads at same time on my 12-threads CPU.

GIF to represent the problem: enter image description here

A snippet from the code is posted below but you can find the entire code for client and server in the pastebins:

// https://pastebin.com/NcA5Vja2 The entire server code
private static void AcceptCallback(IAsyncResult ar)
{
    // Signal the main thread to continue
    _mre.Set();

    TcpListener listener = (TcpListener)ar.AsyncState;
    TcpClient client = listener.EndAcceptTcpClient(ar);

    IPAddress ip = ((IPEndPoint)client.Client.RemoteEndPoint).Address;
    Console.WriteLine($"{ip} has connected!");

    // In production a SSL certificate can be added. More information here: https://docs.microsoft.com/en-us/dotnet/api/system.net.security.sslstream?redirectedfrom=MSDN&view=netframework-4.8
    using (NetworkStream ns = client.GetStream())
    {
        SendMessage(ns, "Mr. Client, hello");

        string result = ReadMessage(ns);
        Console.WriteLine(result);
    }

    Thread.Sleep(5000);

    // Close connection
    client.Close();
    Console.WriteLine($"{ip} has disconnected!");
}

// https://pastebin.com/gVKZy4N6 The entire client code

0 Answers