Search code examples
csocketsposix-select

Need a Proper Data Structure for Handling Message from Multiple Clients


In our application we have a server which will connect to multiple clients. For your reference it is single threaded application . Whenever a client wants to send some message to other client it will go via the server. Whenever a client sends message to the server, it will store the message into a Dqueue. Server will extract messages one by one from the Dqueue and it will call select() and check whether the channel where the message is supposed to be sent is available or not. If yes it will send, otherwise it will insert it into the back so that we can process other messages.But problem with this approach is that, suppose client C1 sends two messages S1 and S2. Now when server tries to send S1 to other client C2, C2 was busy as a result it will push the message S1 into the back of the queue. Now Suppose while processing S2, client C2 is ready.So server can now send S2. But the problem with this is messages will reach to the C2 in reverse order (S2 S1).

Can you please suggest what data structure should be suitable for this so that we can maintain the same message order?


Solution

  • Don't use a single queue to handle all messages. Each client needs its own individual queue. When a message arrives, determine the client it is destined for and put the message at the end of that client's queue. Then update your server logic to send only the top message in a given client's queue to that client. If the client is busy, dont' send the top message. If the client is ready, send the top message and remove it from that clien's queue.