I am starting a very simple echo web server server as shown below:
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 using javascript below
var ws = new WebSocket("ws://localhost:80/websocket");
In the console, I see
new connection
connection closed
I do not understand why I see connection closedin the console. The client also indicates that the connection is closed, but I see no good reason for this. Any help would be greatly appreciated. To perform replication, run python code as admin, open any JS console and enter the JS code. My desired result is that the socket will not be immediately closed. This is somewhat based on what I read in the tornado docs .
change , commenting self.write_message("Hello World")in the method open, the connection does not close. However, running the sample code from the documents now gives something interesting.
var ws = new WebSocket("ws://localhost:80/websocket");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
new connection
message received Hello, world
connection closed
, , connection closed? , self.write_message .