I am using the python tornado framework to write a small web server for a game I'm writing. The get requests are working fine however, when I try to create a websocket connection I get this error in my browser:
Here is my javascript code:
var ws = new WebSocket("ws://localhost:8888/ws");
ws.onopen = function() {
ws.send("ping");
};
Here is the code for the python server:
class StateQueryHandler(tornado.websocket.WebSocketHandler):
def open(self):
state.players = state.players + 1
self.write(state.players)
print("socket opened")
. . .
application = tornado.web.Application([
(r"/ws", StateQueryHandler),#websocket endpoint
(r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "../client"})
])
server = tornado.httpserver.HTTPServer(application)
server.listen(8888)
tornado.ioloop.PeriodicCallback(state.update, 250).start()
tornado.ioloop.IOLoop.instance().start()
Can anyone tell me what is going wrong? Do I have to do anything extra on the server side to keep the tcp connection alive ?
Try this:
class StateQueryHandler(tornado.websocket.WebSocketHandler):
def open(self):
state.players = state.players + 1
self.write_message(state.players)
print("socket opened")
You need to call the method write_message, not write.
Check out the documentation for more info: http://www.tornadoweb.org/en/branch2.4/websocket.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.