pyList

tornado 官方的websocket 示例

服务器与浏览器通过websocket 传送信息

app.py

import logging
from tornado import websocket, web, ioloop
import json

cl = []

class IndexHandler(web.RequestHandler):
    def get(self):
        self.render("index.html")

class SocketHandler(websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        if self not in cl:
            logging.error(id(self))
            cl.append(self)

    def on_close(self):
        if self in cl:
            cl.remove(self)

class ApiHandler(web.RequestHandler):

    @web.asynchronous
    def get(self, *args):
        self.finish()
        id = self.get_argument("id")
        value = self.get_argument("value")
        data = {"id": id, "value" : value}
        data = json.dumps(data)
        for c in cl:
            c.write_message(data)

    @web.asynchronous
    def post(self):
        pass

app = web.Application([
    (r'/', IndexHandler),
    (r'/ws', SocketHandler),
    (r'/api', ApiHandler),
    (r'/(favicon.ico)', web.StaticFileHandler, {'path': '../'}),
    (r'/(rest_api_example.png)', web.StaticFileHandler, {'path': './'}),
])

if __name__ == '__main__':
    app.listen(8888)
    ioloop.IOLoop.instance().start()

index.html

<!DOCTYPE html>
<html>
<head>
  <title>tornado WebSocket example</title>
  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
  <div class="container">
    # tornado WebSocket example
    <hr>
      WebSocket status : <span id="message"></span>
    <hr>
    ### The following table shows values by using WebSocket

      <div class="row">
        <div class="span4">
          <table class="table table-striped table-bordered table-condensed">
            <tr>
              <th>No.</th><th>id</th><th>value</th>
            </tr>
            <tr id="row1">
              <td> 1 </td><td> id 1 </td><td id="1"> 0 </td>
            </tr>
            <tr id="row2">
              <td> 2 </td><td> id 2 </td><td id="2"> 0 </td>
            </tr>
            <tr id="row3">
              <td> 3 </td><td> id 3 </td><td id="3"> 0 </td>
            </tr>
          </table>
        </div>
        <div class="span4">
          <table class="table table-striped table-bordered table-condensed">
            <tr>
              <th>No.</th><th>id</th><th>value</th>
            </tr>
            <tr id="row4">
              <td> 4 </td><td> id 4 </td><td id="4"> 0 </td>
            </tr>
            <tr id="row5">
              <td> 5 </td><td> id 5 </td><td id="5"> 0 </td>
            </tr>
            <tr id="row6">
              <td> 6 </td><td> id 6 </td><td id="6"> 0 </td>
            </tr>
          </table>
        </div>
        <div class="span4">
          <table class="table table-striped table-bordered table-condensed">
            <tr>
              <th>No.</th><th>id</th><th>value</th>
            </tr>
            <tr id="row7">
              <td> 7 </td><td> id 7 </td><td id="7"> 0 </td>
            </tr>
            <tr id="row8">
              <td> 8 </td><td> id 8 </td><td id="8"> 0 </td>
            </tr>
            <tr id="row9">
              <td> 9 </td><td> id 9 </td><td id="9"> 0 </td>
            </tr>
          </table>
        </div>
      </div>

    <hr>
    ### REST API examples
    <ol>
      <li>Set the "id 1" value to 100
        <ul><li>curl "http://hiroakis.com:8888/api?id=1&value=100"</li></ul>
      </li>
      <li>Set the "id 1" value to 300 ( The row No 1 will change to yellow )
        <ul><li>curl "http://hiroakis.com:8888/api?id=1&value=300"</li></ul>
      </li>
      <li>Set The "id 1" value to 600 ( The row No 1 will change to red )
        <ul><li>curl "http://hiroakis.com:8888/api?id=1&value=600"</li></ul>
      </li>
    </ol>
    <ul>
      <li>value 201 - 500 : change to yellow</li>
      <li>value 501 - : change to red</li>
    </ul>
    ![./rest_api_example.png](./rest_api_example.png "")
  </div>
  <script>
    var ws = new WebSocket('ws://localhost:8888/ws');
    var $message = $('#message');

    ws.onopen = function(){
      $message.attr("class", 'label label-success');
      $message.text('open');
    };
    ws.onmessage = function(ev){
      $message.attr("class", 'label label-info');
      $message.hide();
      $message.fadeIn("slow");
      $message.text('recieved message');

      var json = JSON.parse(ev.data);
      $('#' + json.id).hide();
      $('#' + json.id).fadeIn("slow");
      $('#' + json.id).text(json.value);

      var $rowid = $('#row' + json.id);
      if(json.value > 500){
        $rowid.attr("class", "error");
      }
      else if(json.value > 200){
        $rowid.attr("class", "warning");
      }
      else{
        $rowid.attr("class", "");
      }
    };
    ws.onclose = function(ev){
      $message.attr("class", 'label label-important');
      $message.text('closed');
    };
    ws.onerror = function(ev){
      $message.attr("class", 'label label-warning');
      $message.text('error occurred');
    };

  </script>
</body>
</html>

github https://github.com/hiroakis/tornado-websocket-example 5

补充

def on_message(self, result):
    json_result = json.dumps(result)
    if not self.connection_closed:
        try:
            self.write(json_result)
            self.finish()
        except:
            # Catch all, as the client could go away while we're replying.
            self.connection_closed = True

def on_connection_close(self):
    # The client has given up and gone home.
    self.connection_closed = True

---------------------
class WSHandler(tornado.websocket.WebSocketHandler):

    def open(self):
        self.id = uuid.uuid4()
        external_storage[self.id] = {'id':self.id}
        print 'new connection'
        self.write_message("Hello World")

    def on_message(self, message):
        #Some message parsing here
        if message.type == 'set_group':
           external_storage[self.id]['group'] = message.group
        print 'message received %s' % message

    def on_close(self):
        external_storage.remove(self.id)
        print 'closed connection'
本文网址: https://pylist.com/t/1419907739 (转载注明出处)
如果你有任何建议或疑问可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles