问题
When using Websocket++ with the ASIO mode, I start my connection with:
boost::shared_ptr<client> x(new client());
x->init_asio();
websocketpp::lib::error_code ec;
client::connection_pt con = x->get_connection(url, ec);
x->connect(con);
new thread(boost::bind(&LocalCallbacks::run, x)); // which just runs x->run()
This pattern is copied (with modifications) from the examples provided. How should I cleanup properly when a user presses a button to cancel the websocket? I am currently doing:
x->stop();
Should I also be calling x->close()
? Do I need to wait after calling close
before calling stop
? Do I need to kill the thread
that was created, or will that stop automatically? I have had reports of the current code leaving the websocket session open.
回答1:
The ideal method for cleanly shutting down a client endpoint is described at this point in the following tutorial:
https://github.com/zaphoyd/websocketpp/blob/master/tutorials/utility_client/utility_client.md#close-all-outstanding-connections-in-websocket_endpoint-destructor
In short, rather than closing the endpoint, you close connections via con->close()
. This will cleanly perform the WebSocket and TCP closing handshakes (with a configurable timeout to make sure a malicious or broken client doesn't hang forever).
Once all connections running on an endpoint are closed the endpoint stops running and its run() method(s) return. (Except in the case of perpetual mode. If you are using perpetual mode turn it off before closing connections). As such, you can use thread.join()
on your thread running the endpoint after closing connections to wait until they are all closed.
This process is not instantaneous, as it requires a few network round trips to clean everything up. If you must end right now for whatever reason then call endpoint.stop()
. This will immediately cease processing io_service jobs. This will leave all existing connections in a limbo state. WebSocket connections will not appear to have closed on the other end but when they try and write they will get a broken TCP / unclean disconnect error or timeout error. Your local OS may keep sockets open as well tying up resources or ports. You local WebSocket++ connections will all immediately have their close/fail handlers called with an unclean disconnect close code.
来源:https://stackoverflow.com/questions/25260852/shut-down-websocket-connection