Boost asio - read and write at the same time

I am trying to implement two-way communication using boost: asio. I am writing a server that will communicate with several clients.

I want records and readings with clients to occur without any synchronization and order - the client can send a command to the server at any time and still receive some data in a loop. Of course, access to shared resources must be protected.

What is the best way to achieve this? Has two streams - one for reading and one for writing a good option? How about receiving connections and managing many clients?

//edit

โ€œWithout synchronization and orderโ€, I mean that the server must constantly transmit data to clients and that it can respond (change its behavior) to client requests at any time, regardless of what is being sent to them.

+4
source share
2 answers

One key idea of โ€‹โ€‹asio is that you do not need multiple threads to work with multiple client sessions. Your description is somewhat generalized, and I'm not sure I understand what you mean by "I want records and readings with clients to occur without any synchronization and order."

A good starting point is the asio chat server example. Note that in this example, an instance of the chat_session class is created for each connected client. Objects of this class continue to publish asynchronous reads while the connection is live and at the same time they can write data to connected clients. At the same time, the chat_server class chat_server continues to accept new incoming client connections.

+4
source

At work, we do something conceptually very similar, and there I noticed a big impact that a heavy handler has on performance. Writing the side of the code / write handler works too much and takes too long the workflow, thereby compromising the program flow. Especially RST packets (closed connections) were not detected fast enough by the read handler because the write actions took their sweet time and forced most of the processing time into the workflow. I currently fixed this by creating two worker threads, so that one line of code was not hungry from processing time. Admittedly, this is far from ideal, and it is on my long list of optimizations.

In short, you can get rid of using one thread for reading and writing if your handlers are lightweight and the second thread is processing the rest of your program. As soon as you notice strange synchronization problems, it's time to either lighten the network handlers or add an additional thread to the work pool.

+1
source

All Articles