I have a server and has 2 clients connecting to it through TCP. These clients continuously send information to the server. This is a proxy server and relays the messages it receives from the client. But it has to do relay the messages alternately. i.e. message from client A, then message from client B and again A then B and so on. This I can achieve by checking where the message is coming from and then relay messages alternately and ignoring consecutive messages from the same client.
However I also do not want the server to get bogged down if any of the clients disconnects or is not sending messages. If this happens the proxy will continue to wait forever for the some message from the client which is now disconnected (or for some reason not sending message). In this case I would want the server to relay the message from from sole connected client.
Instead I am thinking if something like this is possible. If I get 2 consecutive messages from the same client I would like to check if the other client is read to send me a message. My question is whether it is possible to check from the other client’s socket if there is a message buffered and ready to be sent. In this this case can ignore the consecutive message from the same the client and instead first send the message from the other client. (that I have checked.)
Is this possible? Hope I have asked the question clearly.
Thanks
I am reading the problem as thus:
You have:
1 server
2 clients
Your server gets messages from client 1 and 2 and forwards them.
The clients are different producers, meaning the messages they are sending could potentially be different. What you want is the messages from the clients to be sent alteratively out from your server, but not to ‘wait’ if a client has dropped.
In this scenario, I suggest that you have two queues (client1queue and client2queue) in your server.
You will have to read from the sockets in two seperate threads, and when a message comes in add it to its corresponding queue. client1Socket -> client1queue client2Socket -> client2queue
Then, in a third thread, have the server forward the messages, alternating pulling these messages from client1queue and client2queue.
To solve your problem of ‘not waiting’ if the queue is empty simply skip that queues’ ‘turn.’ This insures sending all messages at the fastest possible rate while still getting all the messages across. The downside is that it only alternates if a message is ready to be sent. You could, of course, have it wait for X amount to see if a message comes for the other queue, but I don’t see why you would want to if the system is supposed to work regardless of the client state.