简体   繁体   中英

Implementing a disconnecting feature

So, let's say I have a client, and to respond to server messages, the client must have a function that listens for them, like in my code:

int Client::loop(void *data)
{
Client *instance = (Client*)data;
for (;;)
{
    boost::array<unsigned char, PACKET_LENGTH> buf;
    boost::system::error_code error;
    // Read any incoming package
    size_t len = instance->socket.read_some(boost::asio::buffer(buf), error);

    if (error == boost::asio::error::eof)
    {
        // Connection closed, return
        return 0;
    }

    DataHeader header = static_cast<DataHeader>(buf[0]);

    switch (header) // Let's see which type of packet the server is sending.
    {
        case GTREG: // Server is sending a GTREG response.
            instance->getRegionResponse(buf);
            break;
        case PLOBJ: // Server is sending a PLOBJ response.
            instance->placeObjResponse(buf);
            break;
        case MOVPL: // WIP.
            break;
        case SYOBJ: // Server is sending an object that other player placed.
            instance->syncObj(buf);
            break;
        default:
            break;
    }
}
}

This function is made a thread by SDL , so that the main process of my program can do work without having to listen to the server. Now, at some point in time, I'll want to close the program, and to do so, I have to disconnect the listening socket.

This "closing function" is called by the main process of my program, so it somehow needs to tell the client thread to shutdown before closing.

Now, how do I do that? I've tried a function like this:

void Client::disconnect()
{
    boost::system::error_code error;
    socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
    socket.close();
}

However, using it crashes the application with an error.

Is there something I'm missing? Thanks in advance for any help!

您应该关闭套接字,然后在关闭套接字之前等待线程终止。

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