简体   繁体   English

使用Boost Asio库打开多个端口

[英]Opening multiple ports using Boost Asio libraries

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). 我是Boost Asio库的新手,我的要求是构建一个服务器,它应该异步监听600个不同的端口(TCP通信)。 Can someone suggest me a smart way to achieve this using Boost Asio. 有人可以建议我使用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; 我尝试过使用Boost Asio文档提供的echo服务器示例,但实际上并不太了解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? 有人可以对此有所了解吗?

The io_service is responsible for handling all I/O that is assigned to it; io_service负责处理分配给它的所有I / O; 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() . 对于您要执行的操作,您需要创建600个单独的服务器实例,然后调用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();

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 . socket变量是单个套接字的实例,对async_connect的调用会建立到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... 您可以以类似的方式对socket执行异步读取和写入,只需确保io_service.run()在某个线程中运行,否则将不会执行异步调用(和关联的回调)...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM