Boost logo

Boost Users :

Subject: Re: [Boost-users] async_send handler problem
From: Alexander Carôt (Alexander_Carot_at_[hidden])
Date: 2013-12-16 14:47:06


P.S.: This is a way simpler program, which behaves in the same way: When
launching the thread before the async_send call it does not work - when
launching it after it does:

/* async_send_to udp example
  * compile with
  * g++ -o udpserver2 udpserver2.cpp -lboost_system -lboost_signals
-lboost_thread
 */
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>

boost::asio::io_service io_service;

void handle_send(const boost::system::error_code& error, std::size_t
bytes_transferred)
{
  std::cout << "async_send_to return " << error << ": " <<
bytes_transferred << " transmitted" << std::endl;
}

/* ./udpserver <host> <port> */

int main(int argc, char *argv[])
{
  if(argc==3){
    //THREAD BFORE ASYNC_SEND
    //boost::thread t = boost::thread
(boost::bind(&boost::asio::io_service::run, &io_service));
    //t.join();

    boost::asio::ip::udp::socket socket(io_service);
    boost::asio::ip::udp::endpoint remote_endpoint;

    socket.open(boost::asio::ip::udp::v4());

    remote_endpoint = boost::asio::ip::udp::endpoint(
    boost::asio::ip::address::from_string(argv[1]),
boost::lexical_cast<int>(argv[2]));

    std::cout << "Send to " << remote_endpoint << std::endl;

    socket.async_send_to(boost::asio::buffer("message", 7),
remote_endpoint,
    boost::bind(&handle_send, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));

    //THREAD AFTER ASYNC_SEND
    boost::thread t = boost::thread
(boost::bind(&boost::asio::io_service::run, &io_service));
    t.join();
  }
  return 0;
}

>>>>void sender::sendIt(char *charBuffer){
>>>[...]
>>>> sj->dFC->io_service.run();
>>>
>>>You should not call io_service::run() inside this function. The normal
>>>pattern is to set up your network code, e.g. from main(), and then call
>>>run() after setup. This call will block (and all Asio callbacks will be
>>>executed from this thread.) If you do not want your main thread to
>>>handle the network code, then you can launch in a separate thread (as
>>>previously suggested.)
>
>Yes, I truly understand this but for some weired reason this doesn't work
>at all. In my case I launch the run function in the constructor of the
>main class right after the sender class had been instantiated:
>
>SJ::SJ(){
>
> /// SENDER INIT
> dFC->mySender = new sender(this);
>
>
> boost::thread t =
>boost::thread(boost::bind(&boost::asio::io_service::run,
>&dFC->io_service));
> t.join();
>
> // OR dFC->io_service.run();
>}
>
>
>In there anything wrong with this ?
>
>Thanks
>
>Alex
>
>
>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net