Is it possible and recommended to create custom handlers for boost::asio? Are there tutorials on how to do it? After searching for quite some time for it I didn't find anything (only custom allocators in boost::asio).
asio currently supports to provide callbacks, using use_awaitable, use_future for std::futures and more. I would like to have an implementation which works with a boost::future or another kind of future (like the one from stlab) rather than a std::future. Of course, I could study the boost source code and try to mimic it, but that seems rather cumbersome with all the portability details.
"all the portability details" aren't so many, and you want them anyways.
Yes, study the source code e.g. for use_future which has an (outdated) implementation on this site:
boost::asio and Active Object which shows how to implement boost::future support
see also Using futures with boost::asio (using futures is not the most usual approach)
Related
I started trying to learn Boost::Asio by reading the documentation and example code. I found things difficult to understand, particularly because the model seemed similar to coroutines.
I then decided to learn about coroutines, starting with this cppcon talk. In the linked talk, the following line was given in an example of coroutine usage. The example was written in 2014, so the syntax may not match C++20 coroutines.
auto conn = await Tcp::connect.Read("127.0.0.1", 1337)
This feels similar to the stated goals of Boost::Asio. However, in the examples section of the Boost::Asio documentation, there is an example that mixes Boost::Asio and C++20 coroutines. (I do not yet understand this example.)
What is the relationship between Boost::Asio and coroutines? Do coroutines replace parts of Boost::Asio? If I am not doing networking, should I still use Boost::Asio? Where do std::async and the senders/receivers proposal fit into all this?
Q. What is the relationship between Boost::Asio and coroutines?
C++20 coroutines are one of the completion token mechanisms provided with any Asio compliant async API
Q. Do coroutines replace parts of Boost::Asio?
Not 1 on 1.
In practice people may feel a lot less need to write asio::spawn (stackful) coroutines, because in practice the stackfulness is rarely required and makes the implementation (very) heavy in comparison. Also, up to Boost 1.81(?) asio::spawn will still depend on Boost Coroutine (work is underway to remove that and implement the functionality directly on top of Boost Context).
Another where C++20 coroutines seem to remove friction is when providing a dual API (sync and async). I've heard people suggest that it is possible to implement the synchronous version in terms of the asynchronous version transparently. I'm not up to speed with the specifics of this pattern (and whether it is ready for production code yet).
Q. If I am not doing networking, should I still use Boost::Asio?
Should? No. But you may. In general, with c++20 coroutines you will want to use some library like cppcoro or indeed Asio. That's because no user-level library facilities have been standardized yet.
In Asio the interesting bits are:
experimental stuff like channels (channel and concurrent_channel), parallel_group, wait_for_{all,one,any}
the general purpose facility coro which has a lot of flexibility. You could see it as the most useful 80% of cppcoro but
all in one relatively simple class template:
coro<T> -> simple generator
coro<T(U)> -> generator with input
coro<void, T> task producing a T
integrated with Asio executors
This documentation is a pretty decent introduction¹, especially when you're familiar with concepts from other libraries/languages.
Q. Where do std::async and the senders/receivers proposal fit into all this?
I'm not sure. I seem to remember Chris Kohlhoff wrote that proposal. The concept may be lurking under the channel/deferred abstractions in Asio already.
¹ Hat tip #klemensmorgenstern
Does anyone have a good pointer to examples which use futures from the Boost thread library with Boost ASIO? I have an existing asynchronous library which uses callback function that I would like to provide a friendlier synchronous interface for.
It is difficult to provide a concise solution without understanding the interactions with the existing asynchronous library. Nevertheless, this answer uses Boost.Future and Boost.Asio to implement an Active Object pattern. When creating a future, consider examining the existing asynchronous library to determine which approach is more appropriate:
boost::packaged_task provides a functor that can create a future. This functor can be executed within the context of Boost.Asio io_service. Some additional level of wrapping may be required to integrate with the existing asynchronous library, as well as work around rvalue semantics. Consider using this approach if the current function calls already return the value.
boost::promise provides a lower level object which can have its value set. It may require modifying existing functions need to accept the promise as an argument, and populate it within the function. The promise would be bound to the handler that is provided to Boost.Asio io_service. As with boost::packaged_task, it may require an additional level of wrapping to deal with rvalue semantics.
Finally, Boost.Asio 1.54 (currently in beta), provides first-class support for C++ futures. Here is the official example. Even if you are unable to currently use 1.54 beta, it may be beneficial to examine the interface and implementation.
Can you please look at this example:
http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/example/cpp11/futures/daytime_client.cpp
It shows how to use std::future with boost asio.
The key point is to include file use_future.hpp:
#include <boost/asio/use_future.hpp>
Then you can write code like that:
std::future<std::size_t> my_future =
my_socket.async_read_some(my_buffer, boost::asio::use_future);
If you need to use boost::future then I'd suggest to implement another variant, similar to boost::asio::use_future.
The file use_future.hpp is a good example for that.
I have recently been using pthreads on Linux and want to start looking into using boost threads in the near future. I have never used MS visual studio so I don't know the approach there but I (have to) use Embarcadero C++ Builder (formerly Borland) one of the few good things I find with it is that is has a built in class TThread. This is a class that you can derive from to give nicely encapsulated data and start and terminate functions. I prefer this approach than the pthread way of passing functions and void* being passed into the thread create function. I was wondering if there is some kind of design pattern or structure that is commonly used to provide a more object oriented that encapsulates the functionality of threads in this way? I can try and create it myself, but I cannot be the first person to desire this kind of approach and wondered if there was a "standard" way of achieving it.
Edit: Alternatively, if this is a very bad idea perhaps an illustration of why?
I would consider that the most standard approach would be using the standard thread library (closely related to boost::thread, not 100% the same). I would avoid redesigning what has already been designed, reviewed and verified by a committee of experts.
Also note that for the kind of operations that you mention in the comment you might want to take a look at the future part of the standard library (again similar to the boost counterpart), and in particular to the std::asynch function.
I like the way boost::thread is designed (I saw a similar design in the threading library from Rouge Wave). Basically a thread is started by passing a function to be executed and latter that thread object can be used to join that thread. pthread is very similar in design, but boost::thread is much easier to use.
Node.js has a very good and well thought Net API.
I wonder is there a good C++ only implementation of that API as for example LuaNode do for Lua?
Take a look at node.native - attempt to implement api similar to node.js core lib, but with c++11 (and evented IO is also based on libuv)
There is nothing very similar that I know of.
However there are several reactor frameworks out there which give the same event queue driven environment. For example boost::asio provides an event queue that makes callbacks to handle network events, timers, and arbiatary events that you push onto the event queue.
It's largely the same idea, used in the same way. Howver it's nowhere near as simple as node.js to get started with, and does provide any non-blocking functions other than the basics I said above.
It does provide you with the environment to build your own system though. It's an excellent library, but probably rather lower level than you are looking for. There are other simiar libraries such as ACE and parts of the POCO c++ libraries too, but again, they are lower level than node.js with much less library support.
edit:
I've not looked at it too much but how about this https://github.com/joyent/libuv . This is a library that is used to implement some of the node.js features in a cross platform way. Maybe it's possible to use some of it for what you need?
Boost.Asio is conceptually very similar to Node.js. The primary difference being Asio is implemented as a library and Node.js is a language construct. Asio therefore exposes the event queue, requiring some initial setup to post callback handlers, and eventually a blocking call to start the event loop (io_service.run()).
If you're looking for a pure C++ API similar to Node.js, Boost.Asio is definitely the way to go. It is the de-facto networking library for many C++ applications. It's also discussed heavily on SO in the boost-asio tag.
I'm quite sure you could embed a Javascript engine into your program
v8 (building guide)
SpiderMonkey (building guide)
Actually tying that to your C code needs tinkering with the eval functions of both, but I think I remember seeing sample programs doing that for both engines
I really thought this would be easier to find...
I need a portable c++ sockets wrapper. I'm planning to use it for a windows server application and a client that will be running on a embedded device running ulinux (or something similar). I would use Boost but I need it to be lightweight and easy to add to the embedded device project.
Also I would like it to be a "higher level" wrapper... so it starts a background thread to read data and informs be over a callback...
Any ideas?
I'd suggest Boost.Asio. Despite it's name, you are not forced to use asynchronous I/O. You could use synchronous I/O and threads, as your question implies.
Boost.Asio is a cross-platform C++
library for network and low-level I/O
programming that provides developers
with a consistent asynchronous model
using a modern C++ approach.
Just learn to use the socket API directly. You can then easily wrap it yourself. It's not that hard, and you can get started with Beej's excellent guide. As Beej says:
The sockets API, though started by the
Berkeley folk, has been ported to many
many platforms, including Unix, Linux,
and even Windows.
In his guide he details the very small addition you need to do to get the same API in Windows and *nix systems.
Once you've learned, wrap it yourself if you're so inclined. Then you can control exactly how "lightweight" you want it.
If you really don't like Boost asio then you might like the sockets support in dlib. It is simpler in the sense that it uses traditional blocking IO and threads rather than asio's asynchronous proactor pattern. For example, it makes it easy to make a threaded TCP server that reads and writes from the iostreams. See this example for instance. Or you can just make a simple iosockstream if not acting as a server.
I know this is old, but there is a very nice and simple implementation in below location which I'm using for personal use. Had implemented my own wrapper a while back but lost the code and found this one online which is much better than mine:
http://cs.ecs.baylor.edu/~donahoo/practical/CSockets/practical/
Take a look at ENet http://enet.bespin.org/ it is very lightweight and portable and works on top of UDP, with optional support for reliable packets. It is easy to use, the API is low-level and with little performance overhead. You have a high degree of control over the memory management, which could be good if networking is a bottleneck for you and the malloc/new implementation you use performs badly under multithreading.
It would not be that hard to implement your high level thread “optimally”, since there is optional support for blocking receive and the library is a “library” and not a framework therefore you are the decision maker instead of the library.
Perhaps you can have a look at http://www.pt-framework.org/
Old question, but for C++, BSD style synchronous sockets this is about as minimal baggage wrapper as you can find
http://code.google.com/p/ting/source/browse/trunk/src/ting/net/
It does come with exceptions. You could make a bit more lightweight one as a header-only template library, and maybe make exceptions optional, but that would change the API a bit
POCO network classes are quite similar, but do require more dependencies from other parts of the Poco lib
I'm personally creating my own AsIO wrapper for both TCP and Serial sockets, and I started by reviewing the following tutorial:
https://www.gamedev.net/blogs/blog/950-they-dont-teach-this-stuff-in-school/
and
https://objectcomputing.com/resources/publications/mnb/multi-platform-serial-interfacing-using-boost-a-gps-sensor-and-opendds-part-i/
I found the first one very useful and simple to understand.
C++CSP2
Used it loved it. Stable and powerful