I created a secure WebSocket server using the ws4py.websocket package.
A javascript client connects to this Websocket and sends some JSON messages to it.
Now when my JS client closes the connection (function disconnect), it takes about 30 secondes before the server's closed function gets called
Here's the code:
Server
class ControlWebSocket(WebSocket):
def opened(self):
print("Client connected")
def closed(self, code, reason=None):
print("Connection closed [%d]" % (code))
def received_message(self, m):
#some business logic using 'm'
server = make_server('', 8999, server_class=WSGIServer, handler_class=WebSocketWSGIRequestHandler, app=WebSocketWSGIApplication(handler_cls=ControlWebSocket))
server.socket = ssl.wrap_socket (server.socket, certfile='./cert.pem', keyfile='key.pem', server_side=True)
server.initialize_websockets_manager()
server.serve_forever()
Client
ws = new WebSocket("wss://192.168.42.1:8999/");
ws.onopen = function() {
console.log("Connected to WebSocket server");
};
ws.onmessage = function(e) {
//some business logic using e
};
ws.onclose = function() {
console.log("Disconnected from WebSocketServer");
};
function disconnect() {
console.log("Disconnecting from WebSocketServer");
ws.close();
}
Any clues on why this is so long to close the connection ? Are there any ways to terminate the connection faster ?
This your client side issue. If you look in the
wsmodule. At the top you haveAnd then you have below code
Which is to ensure the connection doesn't close before 30 second and gives each party enough time to cleanup the connection. This time is a
constand notconfigurableas such. But if you want the termination to happen instantly you can add aws.finalize()afterws.close()and it would disconnect immediatelyEdit-1
After digging deeper it seems the
ws4pyhas some stuff not in accordance to rfc6455.When you do a close from NodeJS, it sends a close frame of
\x88\x80which indicates that connection should be closed and a close frame should be sent. The filews4py/streaming.pyhas some issues where it doesn't respond to this frame properly. It basically expects more data to be read and gets stuck waiting for the same. This cause the connection to be closed from the client side with the default 30 second timeout.So this is a bug in the python library which you are using. I created a client using NodeJS
WebSocket.serverit closed properly.Why don't you use the Server in NodeJS itself? There is a great example for doing the same at below link
https://github.com/websockets/ws/blob/master/examples/ssl.js
code here for reference