w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Using futures with boost::asio
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.

Categories : C++

error: no type named 'const_iterator' in 'class boost::asio::mutable_buffer' when trying to read using boost::asio::async_read
The buffer parameter given to the async_read() free function needs to meet the MutableBuffer sequence requirements. You should use mutable_buffers_1 instead of mutable_buffer. void Connection::asyncReceiveHeader() {     Buffer* header = new Buffer(packetHeaderSize);     ba::mutable_buffers_1 buffer = ba::buffer(header->pointer(), header->size());     auto readHandler = bind(&Connection::headerReceived, this, ba::placeholders::error, ba::placeholders::bytes_transferred, header);     ba::async_read(socket, buffer, readHandler); }

Categories : C++

can I use a boost::shared_ptr when creating&accepting a socket in boost::asio async mode?
This line is where the magic lives: acceptor_.async_accept(new_sess->socket(),//<-used it for async connection acceptance boost::bind(&ConnectionServer::handle_accept, this, boost::asio::placeholders::error, new_sess)); The async_accept has an (optional) second parameter - a completion function which you are using here. You are using boost::bind to create a functor that matches the completion function declaration. You are passing a new_sess smart pointer to that handler (this is why the smart_pointer is not deleted when you leave the scope). In other words: The async_accept function takes either a functor with no parameters or a functor that accepts an error. You may now create a class that overloads the operator() with that signature. Instead you use

Categories : C++

Boost.Asio on Android failing with Service Not Found (Boost 1.53; NDK r8e)
It means that the OS can't figure out which port stands for http. On most POSIX-compliant systems this mapping is done in /etc/services file, and if http line is missing there, you'll get "service not found" error. I don't know whether Android has this file or not (older versions didn't support it at all, the services were hardcoded in bionic), but if you get the above error, the only workaround is to set the desired port manually: tcp::resolver::query query(tcp::v4(), yourHost, "80");

Categories : Android

./Configure for non-boost ASIO
If you got it from a tarball, you should already have a configure script ready to be executed. If you checked from the repository, you probably need to run ./autogen.sh to generate the configure script for you, using configure.ac as input. The convention is: ./bootstrap: it invokes autoconf to process configure.ac and spit out configure. Often it also invokes automake to process all Makefile.am files and turn them into Makefile.in. Many moons ago, the name autogen.sh was used instead of bootstrap. And configure.in was used instead of configure.ac. ./configure: detects everything on the system and creates config.status, then executes it. ./config.status: processes all *.in files into versions without the .in suffix. That includes Makefile.in -> Makefile. You don't have to run this script

Categories : C++

Cannot use movable objects with Boost.Asio
You need to have BOOST_ASIO_HAS_MOVE defined before including the ASIO headers. If you don't, move support is disabled. See asio/basic_stream_socket.hpp. https://svn.boost.org/trac/boost/ticket/8959

Categories : C++

boost asio udp async_read_from buffersize
A buffer size is required. UDP preserves message boundaries. When data is read from a socket, it will read up to the message boundary, even if the size of the provided buffer is smaller than the message. When the message size is less than that of the buffer, the error code will be set to boost::asio::error::message_size. Either allocate a buffer large enough to read the maximum expected message size or use reactor-style operations to lazily allocate the buffer.

Categories : C++

boost asio client authentication
Yes you have to accept the connection in order to know if it's from your application or not. You can use a three-way handshake at the connection step: Client connects to the server The server is sending an specific value (integer, strings or whatever) to the new client. The client handles this value, compute a new one with it and sends the new value to the server. The server checks if the returned value is correct or not. The client will have the same compute method as the server. The others applications will not be able to use your service if they returned a bad value.

Categories : C++

boost asio netbeans error
try to put to your command line -D_WIN32_WINNT=0x0601 -DWINVER=0x0601 or -D_WIN32_WINNT=0x0501 -DWINVER=0x0501 Windows versions

Categories : C++

C++ Boost.ASIO async_read_until slow
Lets look at the handlers log [2013-07-05 15:58:39 - Thread 7fae57e3f700]: Incoming connection (0ms elapsed) @asio|1373054319.874916|506*508|socket@0x7fae50004f98.async_receive @asio|1373054319.874963|506*509|socket@0x7fffd40fed68.async_accept @asio|1373054319.875008|<506| @asio|1373054320.609088|>508|ec=system:0,bytes_transferred=512 @asio|1373054320.609233|508*510|socket@0x7fae50004f98.async_receive @asio|1373054320.609264|<508| @asio|1373054320.609284|>510|ec=system:0,bytes_transferred=404 [2013-07-05 15:58:40 - Thread 7fae57e3f700]: Received packet headers (638 bytes) - 734ms elapsed From log we can see async_receive is called twice: first is called(#508) 734ms after handler setup(#506). Now, second async_receive is called(#510) 53 microseconds after handler setup(#508).

Categories : C++

boost asio example compilation error
Your compilation command probably should start with g++ -Wall -g -I/usr/include/boost where -Wall asks for all warnings, -g asks for debugging information, and -I/usr/include/boost adds an include directory to the include path. And you really should use a builder like GNU Make. It is time to learn how to write a Makefile. Then you should add in your Makefile a line like CXXFLAGS= -Wall -g -I/usr/include/boost If request.hpp is your own file in the current directory (not one from some system library), you should include it with double-quotes characters like #include "request.hpp" and not use <request.hpp> or else add -I. to your compilation command. Be sure with the pwd and ls commands that you are running the compilation in the right directory. The ls command should show

Categories : C++

How to write to a boost::asio::mutable_buffer?
boost::asio::buffer_cast<>() is what you should use to get access to the pointer used by the buffer. boost::asio::buffer_size() is what you should use to get access to the size used. e.g. const std::string test("test"); const size_t len = std::min(boost::asio::buffer_size(mybuf), test.length()); memcpy(boost::asio::buffer_cast<void *>(mybuf), test.c_str(), len); const std::string test2("test"); boost::asio::mutable_buffer offset = mybuf + len; const size_t len2 = std::min(boost::asio::buffer_size(offset), test2.length()); memcpy(boost::asio::buffer_cast<void *>(offset), test.c_str(), len2); boost::asio::mutable_buffer offset2 = offset + len2; See also: buffer_cast() buffer_size()

Categories : C++

Why do we need to use boost::asio::io_service::work?
When the io_service::run method is called without a work object, it will return right away. Typically, that is not the behavior most developers are looking for. There are of course some exceptions, but most developers are looking to specify a thread to handle all of the asynchronous processing and don't want that thread to exit until told to do so. That is what your code example does. The io_service::run method is specified as a delegate or function pointer in the create_thread methods. So, when the thread is created from the create_thread method it will call the io_service::run method and it passes the io_service object as an argument. Typically one io_service object can be used with multiple socket objects. The stop method is usually called when shutting down the application or wh

Categories : Misc

Sending TCP SYN packet with Boost::Asio
The TCP stack usually deals with this, not your code. If you just call boost::asio::ip::tcp::socket::connect() on an appropriately constructed instance, you will cause a TCP SYN packet to be sent, along with the rest of the TCP handshake and session handling. Update: If you want to implement TCP yourself you will need to deal with more than just a TCP SYN, otherwise you're just writing code to attack systems with half-open connections. You need a raw socket and you need to construct the contents of the packet yourself. If you are doing this you should be able to RTFM to find out more.

Categories : C++

Issue with broadcast using Boost.Asio
I am a bit surprised this works on the same machine. I would not have expected the client, listening to port 1666, to receive data being sent to the broadcast address on port 8888. bind() assigns a local endpoint (composed of a local address and port) to the socket. When a socket binds to an endpoint, it specifies that the socket will only receive data sent to the bound address and port. It is often advised to bind to address_v4::any(), as this will use all available interfaces for listening. In the case of a system with multiple interfaces (possible multiple NIC cards), binding to a specific interface address will result in the socket only listening to data received from the specified interface[1]. Thus, one might find themselves obtaining an address through resolve() when the appli

Categories : C++

Boost.Asio segfault, no idea why
I think I found out the issue. Note the declaration order of the members of Server: boost::shared_ptr<Connection> connection; boost::asio::io_service io_service; boost::asio::signal_set signal_monitor; Destruction order is done in the opposite order of declaration. This means that first signal_monitor, then io_service and finally connection get destroyed. But connection contains a boost::asio::ip::tcp::socket containing a reference to io_service, which got destroyed. And indeed, this is pretty much what happening, and causes a segfault too: int main(int argc, char **argv) { auto io_service = new boost::asio::io_service(); auto socket = new boost::asio::ip::tcp::socket(*io_service); delete io_service; delete socket; return 0; } Declaring connection after i

Categories : C++

How to specify a specific NIC to be used in an application written in c++ (boost asio)
You should open() and bind() the socket to an endpoint before connecting. In this example I'm binding it to the loopback interface, in your scenario you can bind to the interface for your NIC. #include <boost/asio.hpp> int main() { using namespace boost::asio; io_service ios; ip::tcp::socket sock( ios ); sock.open( ip::tcp::v4() ); sock.bind( ip::tcp::endpoint(ip::address::from_string("127.0.0.1"), 0) ); sock.connect( ip::tcp::endpoint(ip::address::from_string("127.0.0.1"), 1234) ); } I'm not a Windows programmer so I can't provide a more detailed example than this. I believe you can enumerate through the NIC interfaces using GetAdaptersAddresses. On Linux I would use getifaddrs(3).

Categories : C++

Random EOF in boost asio in multi thread
This is a bug of boost::asio 1.54.0 I found two similar threads on the internet: this one. and that one (on stack overflow). There is also a bug report here. I installed boost 1.53 and it is now working just fine.

Categories : C++

How to trick boost::asio to allow move-only handlers
Until Chris Kohlhoff responds to the bug I've filed, here's a simple workaround: template <typename F> struct move_wrapper : F { move_wrapper(F&& f) : F(std::move(f)) {} move_wrapper(move_wrapper&&) = default; move_wrapper& operator=(move_wrapper&&) = default; move_wrapper(const move_wrapper&); move_wrapper& operator=(const move_wrapper&); }; template <typename T> auto move_handler(T&& t) -> move_wrapper<typename std::decay<T>::type> { return std::move(t); } The wrapper declares a copy constructor, tricking asio's machinery into submission, but never defines it, so that copying would result in a linking error. Now one can finally do this: std::packaged_task<int()> pt([] { st

Categories : C++

boost::asio::async_read get end of file error
An eof error indicates that the writer side closed the connection. Any data sent before that should still be available in the TcpServer::HandleRead callback. Check the bytes_transferred parameter to find out how much data was received by the reader.

Categories : C++

Is there any way to asynchronously wait for a future in Boost Asio?
How about using the work concept? io_service::run will run as long as the work is available and will terminate when work is deleted as soon as there is no unfinished task. Before calling run you create a work instance: boost::shared_ptr<boost::asio::io_service::work> work( new boost::asio::io_service::work( io_service) ); And in your other thread you call as soon as you want to allow io_servce::run to terminate. work.reset(); see also http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.stopping_the_io_service_from_running_out_of_work

Categories : C++

how to verify client certificates using boost::asio SSL?
Finally got the solution. One of my teammate has suggested to use flag boost::asio::ssl::verify_fail_if_no_peer_cert in association with boost::asio::ssl::verify_peer and it worked. updated line of code : context_->set_verify_mode(boost::asio::ssl::verify_peer | boost::asio::ssl::verify_fail_if_no_peer_cert);

Categories : C++

boost::asio - collisions between servers, two-way communication
This is a simple race condition. You'd want to implement some sort of atomic lock variable or semaphor or flag, so if one server is about to send a request to another, it will from that moment reject any incoming requests from other servers. I'd probably use std::atomic to implement this.

Categories : C++

Charset used by boost-asio error message
After digging into boost on my system, I found that the included hpp files include an ipp file which in turn calls the OS functions. If there is an error, only the code of the error is known at this stage. The real error message is formed when the message() function is called. The implementation on windows calls FormatMessageA or FormatMessageW depending if BOOST_NO_ANSI_APIS is defined: std::string system_error_category::message( int ev ) const { # ifndef BOOST_NO_ANSI_APIS LPVOID lpMsgBuf = 0; DWORD retval = ::FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ev, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPSTR) &lpMsgBuf,

Categories : C++

Clear boost::asio::io_service after stop()
io_service::stop() and io_service::reset() only control the state of the io_service's event loop; neither affect the lifespan of handlers scheduled for deferred invocation (ready-to-run) or user-defined handler objects. The destructor for io_service will cause all outstanding handlers to be destroyed: Each service object associated with the io_service will have its shutdown_service() member function invoked. Per the Service type requirement, the shutdown_service() member function will destroy all copies of user-defined handler objects that are held by the service. Uninvoked handler objects scheduled for deferred invocation are destroyed for the io_service and any of its strands. Consider either: Controlling the lifespan of the io_service object. One approach can be found in this

Categories : C++

Why is boost::asio::async_write causing a crash?
This is fraught with peril: std::vector<boost::asio::const_buffer> buffers; buffers.push_back(boost::asio::buffer(outboundHeader)); buffers.push_back(boost::asio::buffer(outboundData)); boost::asio::async_write(socket, buffers, handler); Because buffers is a local object with automatic storage duration, it is going out of scope before the async_write() is complete. That alone shouldn't be an issue (this object is copied as necessary). However, your actual data (held in outboundHeader and outboundData) are also from local objects with automatic storage duration, so they also are going out of scope before the async_write() is complete. You have to ensure that the objects passed into the async_* functions have lifetimes that extend to the point that the handler is called. Here's

Categories : C++

Boost::Asio Multicast listen address
I struggled with this issue for some time. I finally found this explanation. This code from that post caused my socket to bind to the correct interface: std::string address_listen = "1.2.3.4"; std::string address_mcast = "224.0.0.0"; unsigned short address_port = 50000; boost::system::error_code ec; boost::asio::ip::address listen_addr = boost::asio::ip::address::from_string(address_listen, ec); boost::asio::ip::address mcast_addr = boost::asio::ip::address::from_string(address_mcast, ec); boost::asio::ip::udp::endpoint listen_endpoint(mcast_addr, address_port); socket.open(listen_endpoint.protocol(), ec); // boost::asio::ip::udp::socket socket.set_option(boost::asio::ip::udp::socket::reuse_address(true), ec); socket.bind(listen_endpoint, ec); socket.set_option(boost::asio::ip::multicas

Categories : C++

Boost::asio UDP Broadcast with ephemeral port
OK, I found a solution to this issue. Under linux it's not necessary, but under windows I discovered that if you are neither binding nor connecting, you must have transmitted something before you make the call to asynch_recieve_from(), the call to which is included within my this->asynch_receive() method. My solution, make a dummy transmission of an empty string immediately before making the asynch_receive call under windows, so the modified code becomes: m_socketPtr->set_option(boost::asio::socket_base::broadcast(true)); // If no local port is specified, default parameter is 0 // If local port is specified, bind to that port. if(localPort != 0) { boost::asio::ip::udp::endpoint localEndpoint(boost::asio::ip::address_v4::any(), localPort); m_socketPtr->bind(localEndpoint); } i

Categories : Windows

boost::asio UDP send/receive in the same process
ok second try :D but this time i checked it. your problem is you are using the same endpoint for send and receive. and the i found also this: In general, it is safe to make concurrent use of distinct objects, but unsafe to make concurrent use of a single object. However, types such as io_service provide a stronger guarantee that it is safe to use a single object concurrently. so create one endpoint for your txsock and one for rxsock -> sending to send_end/ receiving from rec_end i got this result. send(2006) receive(2006) receive(2006) send(2006) receive(2006) send(2006) receive(2006) send(2006) send(2006) receive(2006) receive(2006) send(2006) send(2006) receive(2006) receive(2006) send(2006) received 8 packet(s) total receive(0) receive error: The I/O operation has been aborted

Categories : C++

Boost Asio pattern with GUI and worker thread
If you have only one worker, then it's rather easy. ASIO's handlers are executed by the thread(s) that are calling io_service.run(). In your case, that means that only one thread, the worker one, can execute callback handler. So you need not to worry about thread safety here. Your GUI thread, assuming that it has access to one's socket, can call boost::asio::async_write() without problem. The callback handler, however, will be executed in the worker thread. From my experience (admitedly limited), I used this pattern: The business logic thread (could be your GUI thread) can schedule a write to one of its client easily, by calling boost::asio::async_write(): the worker thread will take care of it. The worker thread start some boost::asio::async_read(), and could be building "business lo

Categories : C++

How to cancel boost asio io_service post
You cannot selectively cancel callbacks in such a manner through an io_service. One option is to move the logic to a higher level, such as inside of MyClass. A sample implementation may be: class MyClass : public boost::enable_shared_from_this<MyClass> { public: typedef boost::shared_ptr<MyClas> Ptr; static Ptr create( boost::asio::io_service& io_service ) { const Ptr result( new MyClass ); io_service.post( boost::bind(&MyClass::myCallback, result) ); return result; } void myCallback() { if ( _canceled ) return; } void cancel() { _canceled = true; } private: MyClass() : _canceled(false) { } private: bool _canceled; }; This class uses a boost::shared_ptr to enforce shared ownership semantics. Doing

Categories : C++

boost::asio accepting socket error already open
temp is a local object, it gets destroyed immediately on BeginAccept exit. This means that async_accept works with a danging reference, which is undefined behavior. Make temp a member (it would be also a good idea to give it more meaningful name).

Categories : C++

C++11 thread crash when access boost::asio::ip::tcp::socket
That's the difference between boost::thread and std::thread. I have seen the code, and you can fix it to work with std::thread, just like this: void server(boost::asio::io_service& io_service, short port) { // ... std::thread t(boost::bind(session, sock)); t.detach(); } It seems you must detach or join the thread when you use std::thread. Code: #include <iostream> #include <thread> int main(void) { std::thread t([](){std::cout << "will throw exception" << std::endl;}); // t.detach(); return 0; } It will throw exception if not detach or not join or not link pthread

Categories : Multithreading

boost::asio::async_write gets to the other side with a started string
You are generating multiple concurrent calls to async_write(). These calls are not guaranteed to be atomic or in sequence. The reason is that async_write() is implemented in terms of multiple calls to async_write_some(), the caller must make sure that there is only one async_write() in progress as any one time. A better approach would be to dequeue the first command from your queue and start up the next write in the completion handler. That could be a cause of a spurious byte you don't expect. The other thing to check is that your vectors really contain what you think they contain. Check this using a debugger or emitted log output.

Categories : C++

boost::asio: Is there any name for the "strand" type of synchronization primitive?
I am not aware of an official name for the construct. The proposal based on Boost.Asio (N2175 - Networking Library Proposal for TR2) documents the strand class, but does not reference any relevant material. Also, the Intel compiler documentation makes a few references to strand in its execution model, defining it as "any sequence of instructions without any parallel control structures."

Categories : C++

Hybrid tcp::iostream and socket operation with Boost.Asio
Finally I didn't used the stream at all. They seemed to be easy/friendly to use, but they doesn't allow asynchronous operations. I realized that mixing synchronous and asynchronous operations was not a good idea. Adding asynchronous operation to the queue help to balance the load of the server. Conclusion: You should only use asynchronous operations because Boost.Asio is mainly designed for them.

Categories : C++

how to use boost::asio::write_at, in particular have prombel with param meaning
First parameter is an object supporting SyncRandomAccessWriteDevice concept. One model of this concept is windows::random_access_handle.

Categories : Networking

Boost::Asio HTTP Server extremely slow
About HTTP server 3 example. Look at the request_parser source code. The methods parse/consume. It is really not optimial cus it getting data from buffer byte-by-byte and working with each byte; pushing into std::string using push_back and so on. Its just an example. Also, if you are using asio::strand notice that it uses a mutex t lock "strand implementation". For HTTP server its easily possible to remove asio::strand at all, so i recomment to do this. If you want to stay with strands - to avoid delays on locking you can set those defines at compile time: -DBOOST_ASIO_STRAND_IMPLEMENTATIONS=30000 -DBOOST_ASIO_ENABLE_SEQUENTIAL_STRAND_ALLOCATION

Categories : C++

Boost.Asio: socket::close not cancelling aysnc_read_some
First, it should cause the handle to be called when the next run,run_one,poll, or poll_one is called, assuming the io_service is still in a valid state. Canceling/closing does not suddenly change the behavior of how handlers are invoked in ASIO. Because of this, if you're triggering this on deletion of your Session, you will have UB, since the handler will be invoked on the destroyed object, since you passed it the raw pointer, which has subsequently been deleted. My usual technique for this is to use shared_ptr combined with a variant of the pimpl pattern. I usually have the implementation in a shared pointer, and pass that to the various ASIO calls. When the exterior interface is destroyed, I call a shutdown method on the pimpl which causes ASIO to cancel its operations, and then t

Categories : C++

HOWTO: post messages between threads with Boost::asio?
The UI thread is it a webkit similar kind of UI or plain windows forms, because if you are using webkit then u can handle it in a different way. OR Try using Delegates. OR finally if nothing works out, you can run a while loop checking an vector for any new input and add to the vector from the thread callback function. I prefer if you could use delegate. (pointer function) Here is a sample code for pointer function: define a function like this: typedef boost::function<void(std::string)> fnLog; or if u want to go specifically for windows then typedef void (__stdcall *fnLog)(char* val); fnLog is the function with std::string parameter. then bind your function which is in UI thread to the pointer function fnLog myPointerFunc = boost::bind( &UI::f1, _1); then pass

Categories : C++



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.