简体   繁体   中英

How to implement a WebSocket server serving only 1 client at a time

I'm using WebSocket++ library to implement a WebSocket server.

Due to the characteristic of my server, I would like it to serve only 1 client at a time. That is, once a client has been connected to my server, I would like it to stop listening from other potential clients until the already connected client disconnects.

Currently my 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 I pause and resume listening, or is there any parameter for limiting number of concurrent clients?

Use validate to decide when to accept or refuse a 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 to make above work you will need to set additional handlers for open, close and 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));

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