Question

I am developing TCP client-server console application. I have N number of clients connected to server. On a server side I need to share M records and each record should be sent only once to client. Each record should be received only by 1 client. For example number of records N=4 and number of clients M=10 and result should be:

record1 – to client1
record2 – to client2
record3 – to client3
record4 – to client4
record5 – to client1
record6 – to client2
record7 – to client3
record9 – to client4 
record10 – to client5

The problem is that the number of records M is fixed, but the number clients N is not fixed (sometimes N=3, sometimes N=5, etc)

Could you please suggest me a solution to organize this type of flow control?

Was it helpful?

Solution

I'd try to implement something like this:

  • You'll need one list or collecting holding all clients being connected. You'll need random access, i.e. you'll have to add clients to the front or back and you'll have to be able to remove any element at any time. Bonus points if the list is sorted by number of assigned records (ascending).

  • When there's a new record to process (or while you iterate over a list with them):

    • Send the record to the client being in front of your list.
    • Remove the client from the front of the list and add it to the back (unless the list is sorted anyway).
  • When a new client connects, it's added to the front of your list.

  • If a client disconnects, it's removed from the list and the records are readded for redistribution.

If I didn't make any mistake while thinking about this, this should ensure that always one of the clients with the least number of tasks will get a new record unless many clients drop mid-processing. In that case a sorted list would be an advantage.

Of course, there's room for optimization and it's not the best strategy if your number of clients doesn't change while processing (and only before you start doing so). In this case you could simply determine the client that's supposed to process record n using i = n % number_of_clients.

OTHER TIPS

You want to loop through all records, and simultaneously loop through clients, but use modulus to ensure you loop back through clients if m > n, like this:

var records = GetRecords(); // size m
var clients = GetClients(); // size n

if (clients.Length == 0)
{
    // return or throw here, depending on your application
}

for (var i = 0; i < records.Length; i++)
{
    var record = records[i];
    var client = clients[i%clients.Length];

    SendRecord(record, client);
}

With this solution, m and n could both be dynamic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top