简体   繁体   中英

boost::asio::acceptor hangs up on win7

I've implemented simple boost::asio program that starts tcp connection. It works perfect on linux (ubuntu 12.04, boost 1_48, gcc 4.6.4), but not on Win7 (boost 1_55, vs2008express).

After accepting few (from 3 to 20) connections it hangs up, and doesn't accept connections anymore. Is it some windows protection problem? I turn off firewall and antivirus.

Here is the code for reference:

#include <iostream>

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

class Session : public boost::enable_shared_from_this<Session>
{
  public:
    Session(boost::asio::io_service &io_) : tcpSocket(io_)
    {
      std::cerr << "session ctor" << std::endl;
    }
    ~Session()
        {
      std::cerr << "session Dtor" << std::endl;
    }
    boost::asio::ip::tcp::socket& getTcpSocket() { return this->tcpSocket; }

private:
    boost::asio::ip::tcp::socket tcpSocket;
};

class Server
{
public:

    static const unsigned int defaultPort = 55550;
    Server();
    void start();

private:

    boost::asio::io_service io;
    boost::asio::ip::tcp::acceptor acceptor;

    void startAccept();
    void handleAccept(boost::shared_ptr<Session> s_,
          const boost::system::error_code& e_);
};

Server::Server()
    : acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), defaultPort))
{
}

void Server::start()
{
    this->startAccept();
    this->io.run();
}

void Server::startAccept()
{
    boost::shared_ptr<Session> s(new Session(io));

    acceptor.async_accept(s->getTcpSocket(), boost::bind(&Server::handleAccept,
                           this, s, boost::asio::placeholders::error));
}

void Server::handleAccept(boost::shared_ptr<Session> s_,
      const boost::system::error_code& e_)
{
    std::cerr << "handleAccept" << std::endl;

    if(e_)
        std::cerr << e_ << std::endl;

    this->startAccept();
}

int main(int, char**)
{
  Server server;
  server.start();
}

EDIT:

Problem solved. It was Cygwin problem.

It could be that the Win7 acceptor requires the option to reuse the address: ie SO_REUSEADDR.
Try changing your server constructor to:

Server::Server()
: acceptor(io)
{
  boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), defaultPort);
  acceptor.open(endpoint.protocol());
  acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
  boost::system::error_code ec;
  acceptor.bind(endpoint, ec);

  if(ec)
    // raise an exception or log this error, etc.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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