用tornado实现一个简单的websocket样例

想用SPRING MVC,NODE.JS EXPRESS,TORNADO实现同一个功能,开阔一下视野。

先来TORNADO的吧。。

客户端代码都差不多,主要是服务端代码。

TORNADO的说法:

http://www.tornadoweb.org/en/stable/websocket.html

Override on_message to handle incoming messages, and use write_message to send messages to the client. You can also override open and on_close to handle opened and closed connections.

 

websocket事件说法:

https://html.spec.whatwg.org/multipage/comms.html#network

用tornado实现一个简单的websocket样例_第1张图片

服务端代码:

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)
        print message
        self.write_message(u"hahhahahah")

    def on_close(self):
        pass


class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("websockets.html")


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/', IndexPageHandler),
            (r'/ws', WebSocketHandler)
        ]

        settings = {
            'template_path': 'static'
        }
        tornado.web.Application.__init__(self, handlers, **settings)


if __name__ == '__main__':
    ws_app = Application()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

js代码:

<title>Tornado WebSocketstitle>

 
 
<strong>Message to Send:strong> <input type="text" id="msg" maxlength="25">
 <input type="button" onclick="sendMsg();" value="Send">
 
 <script type="text/javascript">
     
  
  function sendMsg() {
      if ("WebSocket" in window) {
          var ws = new WebSocket("ws://localhost:8888/ws");
            ws.onopen = function() {
               ws.send("Hello, world");
            };
            ws.onmessage = function (evt) {
               alert(evt.data);
            };
      
      }
  }
script>

样子:

用tornado实现一个简单的websocket样例_第2张图片

你可能感兴趣的:(用tornado实现一个简单的websocket样例)