oatpp-websocket icon indicating copy to clipboard operation
oatpp-websocket copied to clipboard

how to reject a connection in server side ?

Open XDinEuro opened this issue 3 years ago • 7 comments

Hi, I am using oatpp-websocket example from https://github.com/oatpp/example-websocket/blob/master/.

I have one use case, the server need to decline new connection when there exists two client.

I tried to change the code here from

void WSInstanceListener::onAfterCreate(const oatpp::websocket::WebSocket& socket, const std::shared_ptr<const ParameterMap>& params) {

  SOCKETS ++;
  OATPP_LOGD(TAG, "New Incoming Connection. Connection count=%d", SOCKETS.load());

  /* In this particular case we create one WSListener per each connection */
  /* Which may be redundant in many cases */
  socket.setListener(std::make_shared<WSListener>());
}

to

void WSInstanceListener::onAfterCreate(const oatpp::websocket::WebSocket& socket, const std::shared_ptr<const ParameterMap>& params) {
    SOCKETS++;
    OATPP_LOGD(TAG, "New Incoming Connection. Connection count=%d", SOCKETS.load());
    if (SOCKETS >= 3) {
        SOCKETS = 2;
        OATPP_LOGD(TAG, "More than two socket connected, will not listen to new ones");
        socket.sendClose();
    }
    else {
        socket.setListener(std::make_shared<WSListener>());
    }
}

It works properly at first few attemps, but after few times the server stop responding to any connections even though I disconnect the previous two clients.

Another issue is, after I call socket.sendClose(), WSInstanceListener::onBeforeDestroy() is not triggered. Thus I need to manually do SOCKETS = 2.

Is there is better way to gracefully cut down the connections, or more straghtforward,

Is there a way to reject coming connections ?

XDinEuro avatar Jan 24 '23 14:01 XDinEuro

+1

probably you need to accept the connection and close it from listener

madkote avatar Sep 01 '23 12:09 madkote

Hello guys,

TLDR:

socket.getConnection().invalidate();

sendClose just sends a close frame to peer. Then peer has to respond with close frame too. And only after that both sides actually close the connection. - this is the "graceful way".

But the point is that it isn't always possible to follow graceful way due to multiple reasons:

  • client may not follow the protocol
  • connection issue (client changed carrier and connection just hanged)
  • client application hanged
  • any other reason

Your server has to account for all this (using pings/pongs) and drop bad clients.

How to drop connection:

socket.getConnection().invalidate();

lganzzzo avatar Sep 02 '23 00:09 lganzzzo