0

i'm using a synch server and client that reads in an infinite loop.

for (;;){
  boost::system::error_code error;
  read(socket,boost::asio::buffer(&abc, sizeof(abc)));
...
}

what would be the best way to resolve the blocking of the rest of the program since i would like to use snych not asynch. (thread?)

thx in advance..

ddd
  • 481
  • 6
  • 17
  • 1
    make it a thread-per-connection with in/out thread safe queues to communicate to the main thread – bobah Nov 13 '12 at 11:36

1 Answers1

1

make it a thread-per-connection with a thread safe queue to serve as a main thread's inbox. It does not scale for multiple connections, but it is the safest and easiest thing to do when you do not need scalability. Writes will be done by the main thread directly into the socket. Reads will be done by the dedicated thread, it will be accumulating read data bits in a temporary buffer till it has received the whole message and then it would forward the full message into main thread's inbox queue. If you need to serve many connections or are limited in resources, then you need to use non-blocking IO with select()/epoll() based event loop (aka reactor).

bobah
  • 18,364
  • 2
  • 37
  • 70
  • maybe i misunderstand you.. but isn't there a solution where i can leave the server and client as they are but when i call the client start/read from my main function (in c++) that the client starts but the main function also goes on (parallel)? thx.. – ddd Nov 14 '12 at 15:17
  • @ddd - you can't read and do other things by a single thread unless you do non-blocking IO (but in that case things become much more complicated). you either block reading or do other things. This is why you need a separate thread whose sole role will be to always be blocked reading data from socket. – bobah Nov 14 '12 at 20:44
  • ok.. i only need one connection. program starts, client connects and receives data from the server till the end. would you have an example (link) how to implement it? i'm also thinking again of using asynch (would also solve my problem i think!?), but have to make sure everything is transferred correctly. thx.. – ddd Nov 15 '12 at 09:12
  • @ddd - what is client supposed to do with the data it receives? it does matter when defining how exactly the implementation would work. – bobah Nov 15 '12 at 09:15
  • i send an image/array to the client (short array) and it is used @the client as additional information (so 5-10 times per second would be ok). so its important that the whole data receives but it is not such a problem if the client doesnt get every frame from the server – ddd Nov 15 '12 at 12:07
  • it will be much more coding to have it single threaded, but doable: do an asynchronous even loop (reactor pattern) that will be reading from socket when there's anything to read uess there are "interactive" tasks to do in which case it will be serving interactive tasks. Have a look at reactor documentation in ACE framework. – bobah Nov 16 '12 at 10:10