The class must open several sockets, listen asynchronously and write them to the buffer allocated with the class.

In the private: ad section:

 std::vector<SHP_Socket> vecSock; std::vector<udp::endpoint> vecEndpoint; std::vector<uint8_t[8000]> vecData; std::vector<uint8_t[8000]> vecData2; 

where SHP_Socket is: typedef std::shared_ptr<udp::socket> SHP_Socket; .

I initialize sockets as follows:

 SHP_Socket a; udp::endpoint sender_endpoint; a.reset(new udp::socket(io_service_, udp::endpoint(udp::v4(), my_ports[i]))); vecSock.push_back(a); 

Estimated class method that will listen on this socket in a separate thread:

 void Class::receive(const boost::system::error_code &err, std::size_t bytes, int i) { if (bytes > 12) { memcpy(vecData2[i], vecData[i], bytes); } vecSock[i]->async_receive_from(buffer(vecData[i]), vecEndpoint[i], /*[1]*/); } 

It would be desirable that the Class::receive function be passed again by the async_receive_from parameter. How to do it?

    1 answer 1

    If it is hers, use boost::bind / std::bind , but I would do (or so):

     void Class::startRecv(int i) { vecSock[i]->async_receive_from(buffer(vecData[i]), vecEndpoint[i], [this, i](const boost::system::error_code &ec, std::size_t bytes) { if (bytes > 12) { memcpy(vecData2[i], vecData[i], bytes); startRecv(i); // я не знаю по какому критерию передавать i собираетесь. } }); } 

    Or option without lambda:

     void Class::startRecv(int i) { vecSock[i]->async_receive_from(buffer(vecData[i]), vecEndpoint[i], boost::bind(&Class::onRecv, this, _1, _2, i)); } void Class::onRecv(const boost::system::error_code& ec, std::size_t bytes, int i) { if (bytes > 12) { memcpy(vecData2[i], vecData[i], bytes); startRecv(i); // я не знаю по какому критерию передавать i собираетесь. } } 
    • The variable i (denotes the socket \ client index) came from the outside when you first called receive. C lambda I like the way) And do I understand correctly that I need to create for each i I need to run my thread with io_service.run ()? It is assumed that the data is written to the buffer that uses the parent thread. - Dmitry
    • According to the good practices of Asio, I strongly advise you, but in order to parallelize the service, yes, io_service.run() should be called in each thread. - Monah Tuk