Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::asio accepting socket error already open

am not sure what is causing this error Already Open

#include "AsyncServer.h"


AsyncServer::AsyncServer(boost::asio::io_service& io_service, std::string ip, unsigned short port)
    : acceptor(io_service, tcp::endpoint(boost::asio::ip::address_v4::from_string(ip), port))
{

    BeginAccept();
}


AsyncServer::~AsyncServer()
{
}


void AsyncServer::BeginAccept(){
    tcp::socket temp = tcp::socket(acceptor.get_io_service());
    acceptor.async_accept(temp, boost::bind(&AsyncServer::EndAccept, this, boost::asio::placeholders::error));
}

void AsyncServer::EndAccept(const boost::system::error_code& error){

    if (!error)
    {
        //continue with connection
        std::cout << "connected" << std::endl;
    }
    else
    {
        std::cout << error.message() <<std::endl;
    }

    BeginAccept();
}

what am trying to do is pass the socket and the error to EndAccept but it breaks and the error is Already Open , I don't know what's wrong here !

like image 251
Abanoub Avatar asked Oct 25 '25 02:10

Abanoub


1 Answers

temp is a local object, it gets destroyed immediately on BeginAccept exit. This means that async_accept works with a danging reference, which is undefined behavior.

Make temp a member (it would be also a good idea to give it more meaningful name).

like image 145
Igor R. Avatar answered Oct 27 '25 15:10

Igor R.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!