I'm building a client/server architecture in C. When the client program executes it connects to a master program(server) and waits. Then in some moment, the master program has to send some kind of command to the client and the client has to receive that command and perform different kind of actions depending on the command following some internal logic.
Which is the best way to do that?
Should the client be sending packets to the master asking for a command every X seconds? (polling)
Should I use select() in the client?
pd: the client has to send info to the master every X event happens
Which is the best way to do that?
The best way to do it is to have the TCP connection continuously open and the I/O model 100% full-duplex and asynchronous (by which I meant both the client and the server are allowed to send and receive messages across the wire at any time; contrast that to some less flexible systems like HTTP which are based around the idea that the client must first send a request and only then can the server send a response; that's a semantic restriction that makes it difficult to achieve best performance)
Should the client be sending packets to the master asking for a command every X seconds? (polling)
Not if you want good performance -- if you implement it like that, then there will be an unnecessary and unpredictable delay (anywhere from 0 to X seconds) between when a server first has a command available for the client and when the client receives that command.
In general (like amine.ahd mentioned) try to make everything event-driven that you can; polling always involves a tradeoff between wasting network bandwidth (by polling too often) and introducing unnecessary delays (by not polling often enough), and by avoiding polling you can avoid that tradeoff and instead enjoy both very low bandwidth usage and low latency simultaneously.
So if your client is interested in getting some information from the server whenever an event happens, the client should send a single message across informing the server about his interest (or perhaps just making the TCP connection is sufficient to imply that interest?) ... and then the server can simply send the information to the client ASAP whenever an event occurs.
Should I use select() in the client?
You'll almost certainly want to use some I/O multiplexing mechanism in both your client and your server -- whether it be select()
, poll()
, kpoll()
, kqueue()
, WaitForMultipleEvents()
, asyncio, or whatever. I generally use select()
in my code since it's the most common mechanism and so the resulting code can be ported to practically any OS; and select()
has always worked sufficiently well for me that I've never felt the need to use anything different; but if your use case means you don't need to be portable to everywhere, some of the other mechanisms may give you better CPU-efficiency, particularly in cases where you have hundreds or thousands of simultaneous client connections.