Tornado WebSockets 入门

html

<!DOCTYPE html>
<html>
<head>
    <title>Tornado WebSockets</title>
    <script>
        var ws;
 
        function onLoad() {
            ws = new WebSocket("ws://localhost:8080/websocket");
 
            ws.onmessage = function(e) {
               alert(e.data);
            };
        }
 
        function sendMsg() {
            ws.send(document.getElementById('msg').value);
        }
    </script>
</head>
<body onload="onLoad();">
    **Message to Send:** <input type="text" id="msg" maxlength="25" />
     <input type="button" onclick="sendMsg();" value="Send" />
</body>
</html>

服务器

import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
 
 
class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        pass
 
    def on_message(self, message):
        self.write_message(u"Your message was: " + message)
 
    def on_close(self):
        pass
 
 
class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")
 
 
class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/', IndexPageHandler),
            (r'/websocket', WebSocketHandler)
        ]
 
        settings = {
            'template_path': 'templates'
        }
        tornado.web.Application.__init__(self, handlers, **settings)
 
 
if __name__ == '__main__':
    ws_app = Application()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(8080)
    tornado.ioloop.IOLoop.instance().start()
Relative Articles