oatpp / oatpp-websocket

oatpp-websocket submodule.
https://oatpp.io/
Apache License 2.0
78 stars 32 forks source link

Only one or some clients are allowed to connect. #34

Open liu-yabin opened 2 years ago

liu-yabin commented 2 years ago

For server performance reasons. I need to implement only a specified number of client connections. Here is my WsInstanceListener::onAfterCreate() code:

std::atomic<int32_t> WsInstanceListener::sockets_(0);
std::mutex WsInstanceListener::socket_mutex_;

void WsInstanceListener::onAfterCreate(const oatpp::websocket::WebSocket& socket,
                                       const std::shared_ptr<const ParameterMap>& params) {
    std::lock_guard<std::mutex> guard(socket_mutex_);
    sockets_++;
    OATPP_LOGD(kTag, "New incoming connection. Connection count=%d", sockets_.load());
    auto listener = std::make_shared<WsListener>(socket);
    socket.setListener(listener);
    if (sockets_ >= 2) {
        socket.sendOneFrameText("another connection has already established.");
        socket.sendClose();
    }
}

and get the follow error:

 D |2022-03-09 11:05:34 1646795134469424| WsInstanceListener:New incoming connection. Connection count=1
 D |2022-03-09 11:05:37 1646795137843434| WsInstanceListener:New incoming connection. Connection count=2
 D |2022-03-09 11:05:37 1646795137847096| [oatpp::web::protocol::websocket::WebSocket::listen()]:Unhandled error occurred. Message='[oatpp::web::protocol::websocket::WebSocket::readFrameHeader()]: Error reading frame header'
 D |2022-03-09 11:05:37 1646795137849690| WsInstanceListener:Connection closed. Connection count=1

the message another connection has already established. not sended. Is there a way to implement this function.