用tornado實現一個簡單的websocket樣例

想用SPRING MVC,NODE.JS EXPRESS,TORNADO實現同一個功能,開闊一下視野。javascript

先來TORNADO的吧。。html

客戶端代碼都差很少,主要是服務端代碼。java

TORNADO的說法:web

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

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事件說法:app

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

服務端代碼:ide

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代碼:tornado

<title>Tornado WebSockets</title>

 
 
<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>

樣子:oop

相關文章
相關標籤/搜索