Home > database >  Event based communication between sockets
Event based communication between sockets

Time:09-26

I have written a client-server application in c on linux platform. The client, upon receiving data from server will process the same by calling another program through a 'system()' call. In normal course the server socket now waits for the results from the client and the client socket waits for its back-end processing job to be completed so that it can forward the results to the server. However, depending upon occurrence of certain events, the server needs to ask the client to stop processing the current input. Since the present socket states are " server->waiting to receive " and "client -> waiting to send" , how do I reverse the roles in case of an 'event' ? On server side, I can catch the event and change state accordingly, but how do I communicate this change to the client ?

CodePudding user response:

One way to handle it would be to implement full bidirectional communication: i.e. do away with the idea of "socket states" and allow either client or server to send or receive data to each other at any time.

That can be done by having both the client and the server block inside select() (or another similar I/O multiplexing/wait-for-multiple-sockets-at-once call) rather than blocking inside recv(), so that they are able to react to other events besides receiving data from their counterpart.

Another problem you're likely to have is that if your client is blocked inside system() waiting for the background process to exit, it will be difficult for the client to react to incoming data from the server. The solution to that would be to replace the system() call with something more sophisticated, like forkpty(). forkpty() will spawn a child process and give you a file-descriptor that you can read from and/or select() on as if it was a network-socket to the child process's stdin/stdout, allowing your client process to respond to incoming data from both the server and from the child process as necessary.

I used forkpty() to implement the ChildProcessDataIO class of my networking library and found that it works well for that purpose.

  • Related