c++ - 接受器和 Async_Accept 的问题

标签 c++ boost boost-asio

见代码。 :P 我能够在调用 async_accept() 之前接收新连接。我的委托(delegate)函数也从未被调用,因此我无法管理我收到的任何连接,从而使新连接变得无用。 ;)

所以这是我的问题。有没有办法阻止 Boost ASIO 接受器自己获取新连接而只从 async_accept() 获取连接?

谢谢!

AlexSocket::AlexSocket(boost::asio::io_service& s): myService(s)
{
    //none at the moment
    connected = false;
    listening = false;

    using boost::asio::ip::tcp;
    mySocket = new tcp::socket(myService);
}

AlexSocket::~AlexSocket()
{
    delete mySocket;
}

bool AlexSocket::StartListening(int port)
{
    bool didStart = false;

    if (!this->listening)
    {
        //try to listen
        acceptor = new tcp::acceptor(this->myService);
        boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
        acceptor->open(endpoint.protocol());
        acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
        acceptor->bind(endpoint);
        //CAN GET NEW CONNECTIONS HERE (before async_accept is called)
        acceptor->listen();

        didStart = true; //probably change?
        tcp::socket* tempNewSocket = new tcp::socket(this->myService);
        //acceptor->async_accept(*tempNewSocket, boost::bind(&AlexSocket::NewConnection, this, tempNewSocket, boost::asio::placeholders::error) );
    }
    else //already started!
        return false;

    this->listening = didStart;
    return didStart;
}

//this function is never called :(
void AlexSocket::NewConnection(tcp::socket* s, const boost::system::error_code& error)
{
    cout << "New Connection Made" << endl;
    //Start new accept async
    tcp::socket* tempNewSocket = new tcp::socket(this->myService);
    acceptor->async_accept(*tempNewSocket, boost::bind(&AlexSocket::NewConnection, this, tempNewSocket, boost::asio::placeholders::error) );
}

bool AlexSocket::ConnectToServer(std::string toConnectTo, string port)
{
    if (connected)
        return false;

    this->serverConnectedTo = toConnectTo;
    this->serverPort = port;

    ip::tcp::resolver resolver(myService);
    ip::tcp::resolver::query newQuery(toConnectTo, port);
    ip::tcp::resolver::iterator myIter = resolver.resolve(newQuery);
    ip::tcp::resolver::iterator end;

    //error
    boost::system::error_code error = boost::asio::error::host_not_found;

    //try each endpoint
    bool connected = false;
    while (error && myIter != end)
    {
        ip::tcp::endpoint endpoint = *myIter++;
        std::cout << endpoint << std::endl;

        mySocket->close();
        mySocket->connect(*myIter, error);

        if (error)
        {
            //try to connect, if it didn't work return false
            cout << "Did not Connect" << endl << error << endl;
        }
        else
        {
            //was able to connect
            cout << "Connected!" << endl;
            connected = true;
        }
        myIter++;
    }   
    this->connected = connected;
    return connected;
}

编辑: 我已经更改了我的代码以反射(reflect)到目前为止的答案。我正在将 io_service 传递给类(class)的负责人。正如您在下面看到的,main 没有在服务上调用运行,所以我认为应该没有任何东西能够连接,对吧?

我已将调试器置于 listen() 行并转到“canyouseeme.org”。输入 57422 并点击连接。不能。运行 listen() 行。能够连接。这应该不可能吧?从来没有? :(

不知道该怎么办了。 main() 在下面。

int main()
{
    boost::asio::io_service s;
    AlexSocket test(s);

    test.StartListening(57422);

    test.ConnectToServer("localhost", "57422");

    cout << "Enter something to quit" << endl;
    int a2;
    cin >> a2;

    return 0;
}

最佳答案

So here's my question. Is there a way to prevent the Boost ASIO acceptor from getting new connections on its own and only getting connections from async_accept()?

您认为为什么会发生这种情况?如果您发布了完整的代码,那将大有帮助。当我使用您的代码段并在其周围放置样板文件 main 和 io_service::run() 时,一切正常。

#include <boost/asio.hpp>
#include <boost/bind.hpp>

#include <iostream>

using namespace boost::asio;

class Socket {
public:
    Socket(
            io_service& io_service
          ) :
        _io_service( io_service ),
        _acceptor( new ip::tcp::acceptor(io_service) )
    {

    }

    bool start(int port)
    {
        //try to listen
        ip::tcp::endpoint endpoint(ip::tcp::v4(), port);
        _acceptor->open(endpoint.protocol());
        _acceptor->set_option(ip::tcp::acceptor::reuse_address(true));
        _acceptor->bind(endpoint);
        //CAN GET NEW CONNECTIONS HERE (before async_accept is called)
        _acceptor->listen();

        ip::tcp::socket* temp = new ip::tcp::socket( _io_service );
        _acceptor->async_accept(
                *temp,
                boost::bind(
                    &Socket::NewConnection,
                    this,
                    temp,
                    boost::asio::placeholders::error
                    )
                );
    }

    void NewConnection(
            ip::tcp::socket* s, 
            const boost::system::error_code& error
            )
    {
        std::cout << "New Connection Made" << std::endl;
        //Start new accept async
        ip::tcp::socket* temp = new ip::tcp::socket( _io_service );
        _acceptor->async_accept(
                *temp,
                boost::bind(
                    &Socket::NewConnection, 
                    this,
                    temp,
                    boost::asio::placeholders::error
                    )
                );
    }
private:
    io_service& _io_service;
    ip::tcp::acceptor* _acceptor;
};

int
main()
{
    io_service foo;
    Socket sock( foo );
    sock.start(1234);
    foo.run();

    return 0;
}

编译运行:

macmini:~ samm$ g++ -lboost_system accept.cc
macmini:~ samm$ ./a.out 
New Connection Made

从另一个终端远程登录

macmini:~ samm$ telnet 127.0.0.1 1234
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

关于c++ - 接受器和 Async_Accept 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3010426/

相关文章:

c++ - 你能帮我清除这个错误吗

c++ - 函数定义的顺序对于 C++ 中的内联很重要吗

c++ - 日期时间到 UTC

c++ - 在 C++ 中进行松散的 HTML 解析?

c++ - 为什么 C++ 原始类型不像其他类型那样被初始化?

c++ - 线程安全队列是一种好方法吗?

c++ - 用于 boost uuid 的 Visual Studio 2010 调试可视化工具

c++ - 使用 Boost/Asio 时出现 SSL 间歇性问题

c++ - 为 boost socket.connect 设置超时

c++ - 为什么立即销毁的共享指针会泄漏内存?