Xfer: Difference between revisions

From John's wiki
Jump to navigation Jump to search
(asio)
(nowiki)
 
(11 intermediate revisions by the same user not shown)
Line 1: Line 1:
The key class in boost asio is the io_service. It's a singleton, and an uncopyable object (so obviously you need to pass it by ref everywhere), and the key member function of io_service is run().
<nowiki>:)</nowiki>
 
run() is a blocking method - it blocks until it has no more work to do, then it returns, and then that's usually the end of your app. So if you had an app that had no work to do, run() would return immediately and your program would do nothing.
 
To make sure run() always has stuff to do, you assign handlers. So for example, if you were setting up a tcp server, you would create a server socket (and reference the io_service), call the listen method, and then call io_service.run().
 
Important to note that calling the listen method by itself doesn't actually do anything - it just registers a handler with the io_service. it's not until you call run() that anything happens.
 
When a client connects, your handler is called and you accept the connection. But now your listen method has invoked its handler, there is no more work to do, and as soon as your handler is finished, the run() method would exit. So, if you wanted your app to keep going, you need to register another handler - usually by registering another listen() handler.
 
The same goes for read()/write() handlers. If you read something from a socket, generally you'll want to register another read() handler so it can read more when it arrives.
 
And this is where shared_ptrs are just a little bit useful, but may not be all that useful in our case. The shared_ptr just makes sure that a pointer to the Core::Connection (or whatever object we have) doesn't go out of scope and die. If your server didnt maintain a list of active connections (and we werent using shared ptrs) then once you registered a handler for a particular connection (with "this"), then as soon as that method ended, your Connection object goes out of scope. Problem is that when the handler is actually called, the object it is working on is dead, and that's a crash (smiley)
 
In our case though, the only place we are using boost::asio at the moment is for client sockets, so we don't really need to worry about multiple connections, etc. We just hold references to socket objects that won't fall out of scope anywhere, and we then don't need shared_ptrs.

Latest revision as of 20:19, 5 December 2015

:)