c++ - How to implement a WebSocket server serving only 1 client at a time -
i'm using websocket++ library implement websocket server.
due characteristic of server, serve 1 client @ time. is, once client has been connected server, stop listening other potential clients until connected client disconnects.
currently server looks like:
typedef websocketpp::server<websocketpp::config::asio> server; static void onreceivedata(server *s, websocketpp::connection_hdl hdl, server::message_ptr msg) { std::string payload(msg->get_payload()); // process inside payload websocketpp::lib::error_code ec; s->send(hdl, payload, websocketpp::frame::opcode::binary, ec); } int main(void) { server myserver; myserver.init_asio(); myserver.set_message_handler(websocketpp::lib::bind(&onreceivedata, &myserver, websocketpp::lib::placeholders::_1, websocketpp::lib::placeholders::_2)); myserver.listen(9002); myserver.start_accept(); myserver.run(); }
how should pause , resume listening, or there parameter limiting number of concurrent clients?
use validate
decide when accept or refuse connection:
static bool accept_new_connections = true; bool validate(server *, websocketpp::connection_hdl) { return accept_new_connections; } void on_open(server *, websocketpp::connection_hdl hdl) { accept_new_connections = false; } void on_close(server *, websocketpp::connection_hdl hdl) { accept_new_connections = true; }
obviously make above work need set additional handlers open, close , validate:
myserver.set_open_handler(bind(&on_open, &echo_server, ::_1)); myserver.set_close_handler(bind(&on_close, &echo_server, ::_1)); myserver.set_validate_handler(bind(&validate, &echo_server, ::_1));
Comments
Post a Comment