I am running a very simple echo websocket server as below:
#!/usr/bin/python
import datetime
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
class WSHandler(tornado.websocket.WebSocketHandler):
clients = []
def open(self):
print('new connection')
self.write_message("Hello World")
WSHandler.clients.append(self)
def on_message(self, message):
print('message received %s' % message)
self.write_message('ECHO: ' + message)
def on_close(self):
print('connection closed')
WSHandler.clients.remove(self)
@classmethod
def write_to_clients(cls):
print("Writing to clients")
for client in cls.clients:
client.write_message("Hi there!")
def check_origin(self, origin):
return True
application = tornado.web.Application([
(r'/websocket', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(80)
tornado.ioloop.IOLoop.instance().start()
I am connecting to this with javascript as below
var ws = new WebSocket("ws://localhost:80/websocket");
In the console I see
new connection
connection closed
What I do not understand is why I am seeing the connection closed in the console. The client also indicates that the connection is closed but I do not see any good reason for this. Any help would be greatly appreciated. To replicate run the python code as admin, open any JS console and enter the JS code. My desired outcome is for the socket to not be immediately closed. This is somewhat based on what I read in the tornado docs.
edit update by commenting out self.write_message("Hello World") in the open method, the connection does not close. However running the example code from the docs now yields something interesting.
var ws = new WebSocket("ws://localhost:80/websocket");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
server side output is
new connection
message received Hello, world
connection closed
There is no corresponding alert on the client side as expected
The new question is the same as the old which is why does the server say connection closed? It looks like self.write_message may be the culprit.