Opening multiple ports using Boost Asio libraries

霸气de小男生 提交于 2019-12-10 10:15:52

问题


I am a newbie for Boost Asio libraries, my requirement is to build a server, which should listen on 600 different ports asynchronously (TCP communication). Can someone suggest me a smart way to achieve this using Boost Asio. I have tried using echo server example provided at Boost Asio documentation but could not really understand much boost::asio::io_service io_service;

using namespace std; // For atoi.
for(long port=50000;port<=50600;port++)
{
    server s(io_service, port);
    io_service.run();
}

Can someone throw light on this?


回答1:


The io_service is responsible for handling all I/O that is assigned to it; you don't need to create a separate one for each port. For what you are trying to do you will need to create 600 separate server instances then call io_service.run().

vector<shared_ptr<server> > servers;
for (uint16_t port = 50000; port != 50600; ++port)
{
    servers.push_back(shared_ptr<server>(new server(io_service, port)));
}
io_service.run();



回答2:


Try something along the lines of this

boost::asio::ip::tcp::socket socket(io_service);

socket.async_connect(endpoint, connectHandler);

The socket variable is an instance of a single socket, and the call to async_connect sets up an asynchronous connect to the location defined by endpoint. You can perform asynchronous reads from and writes to socket in a similar fashion, just make sure io_service.run() is running in a thread somewhere, or the asynchronous calls (and associated callbacks) won't be executed...



来源:https://stackoverflow.com/questions/9419648/opening-multiple-ports-using-boost-asio-libraries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!