简体   繁体   中英

Boost asio - synchronous write / read - how to do?

First, I want to say that I'm new with Boost asio, and I see a lot of examples but it remains things I don't understand.

I want to create a server, that will accept two clients (it will use two socket). The first client will send messages to the server and the server will send this message to the other client (yes, it is useless to use a server, but it's not the point here, I want to understand how all this work). This will happen until one of the client close.

So, I created a server, the server wait for the clients, and then, it must wait for the first client to send some message. And this is my question: what must I do after?

I thought I need to read the first socket, and then write on the second, and so and so, but how I know if the first client writed on the socket? Same, how I know if the second client read the second socket?

I don't need code, I just want to know the good way to do that.

Thanks a lot for reading!

When you perform async_read you specifify a callback which is going to be called whenever any data is read to the buffer ( you should provide the buffer also, check the async_read's documentation ). Respectively you should provide callback for the async_write to know when your data is already sent. So, from the server perspective, for the client which 'writes' you should do async_read, and for the second client which 'reads' you should do async write. With the offered dataflow client1->server->client2 it is hard to recognize which client the server should read from and which one is write to. It's up to you. You can choose the first connected client as writer and the second as reader, for example.

You might want to start with asio iostreams. It's a high-level iostream-like abstraction above asynchronous sockets.

PS: also, don't forget to run io_service.run() loop somewhere. Because all the asio callbacks are executed within that loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM