0
votes

Boost's official site socket::close() function, see the description

"This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the boost::asio::error::operation_aborted error."


But strangely, when i call chat_session::close(), socket::close() passing ERROR_CONNECTION_ABORTED (1236) error instead of boost::asio::error::operation_aborted (995).

Why is this happens? here is my chat_session class.

class chat_session
    : public boost::enable_shared_from_this<chat_session>
{
public:
    chat_session(boost::asio::io_service& io, chat_server* room)
        : m_sock(io), m_room(room)
    {
    }

    ~chat_session()
    {
    }

    void start()
    {
        m_room.join(shared_from_this());

        m_sock.async_read_some(
            boost::asio::buffer(m_recv_data),
            boost::bind(&chat_session::handle_read, shared_from_this(),
            boost::asio::placeholders::error));
    }

    void close()
    {
        // closing socket. chat_session::handle_read will receive
        // boost::asio::error::operation_aborted error.
        m_sock.close(); 
    }

    boost::asio::ip::tcp::socket& socket()
    {
        return m_sock;
    }

    private:
    void handle_read(const boost::system::error_code& error)
    {
        if (!error)
        {
            printf("RECV -> %s.\n", m_recv_data);

            m_sock.async_read_some(
                boost::asio::buffer(m_recv_data),
                boost::bind(&chat_session::handle_read, shared_from_this(),
                boost::asio::placeholders::error));
        }
        else
        {
            // when i call chat_session::close(),
            // ERROR_CONNECTION_ABORTED (1236) error occurred
            // instead of boost::asio::error::operation_aborted error over here
            ...
            m_room.leave(shared_from_this());
        }
    }

    boost::asio::ip::tcp::socket m_sock;
    chat_room& m_room;
    char m_recv_data[50];
};
1
do you close the sending socket or the receiving socket? Which socket receives the connection_aborted code? Please share a SSCCEsehe

1 Answers

3
votes

Try calling shutdown on the socket first before you close it, as the boost basic_stream_socket::close documentation specifies in the Remarks here:

Remarks

For portable behaviour with respect to graceful closure of a connected socket, call shutdown() before closing the socket.

Try something like the following in your close function:

m_sock.shutdown(boost::asio::ip::tcp::socket::shutdown_receive);
m_sock.close();

If you want to shut down both send and receive, use "shutdown_both" instead of "shutdown_receive".

Funny enough, I've seen this error happen on Windows but not Linux when using an implementation without the call to shutdown.