龙卷风为一个请求推送多个响应

时间:2016-12-13 11:16:13

标签: python python-2.7 websocket tornado

我需要为客户端的每个请求推送多个响应。我正在使用龙卷风为此目的利用龙卷风。

我对龙卷风和我的理解相对较新。

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import socket

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
      print 'new connection'

    def on_message(self, message):
      print 'message received:  %s' % message
      # Reverse Message and send it back
      print 'sending back message: %s' % message[::-1]
      self.write_message('%s:%s' % (i,message[::-1]))

    def on_close(self):
      print 'connection closed'

    def check_origin(self, origin):
      return True

application = tornado.web.Application([
  (r'/ws', WSHandler),
])

如何让on_message函数推送多个请求。

我使用的HTML代码,

<!doctype html>
<html>
  <head>
    <title>WebSockets Hello World</title>
    <meta charset="utf-8" />
    <style type="text/css">
      body {
        text-align: center;
        min-width: 500px;
      }
    </style>
    <script src="http://code.jquery.com/jquery.min.js"></script>
    <script>

      // log function
      log = function(data){
        $("div#terminal").prepend("</br>" +data);
        console.log(data);
      };

      $(document).ready(function () {
        $("div#message_details").hide()

        var ws;

        $("#open").click(function(evt) {
          evt.preventDefault();

          var host = $("#host").val();
          var port = $("#port").val();
          var uri = $("#uri").val();

          // create websocket instance
          ws = new WebSocket("ws://" + host + ":" + port + uri);

          // Handle incoming websocket message callback
          ws.onmessage = function(evt) {
            log("Message Received: " + evt.data)
            alert("message received: " + evt.data);
            };

          // Close Websocket callback
          ws.onclose = function(evt) {
            log("***Connection Closed***");
            alert("Connection close");
            $("#host").css("background", "#ff0000"); 
            $("#port").css("background", "#ff0000"); 
            $("#uri").css("background",  "#ff0000");
            $("div#message_details").empty();

            };

          // Open Websocket callback
          ws.onopen = function(evt) { 
            $("#host").css("background", "#00ff00"); 
            $("#port").css("background", "#00ff00"); 
            $("#uri").css("background", "#00ff00");
            $("div#message_details").show();
            log("***Connection Opened***");
          };
        });

        // Send websocket message function
        $("#send").click(function(evt) {
            log("Sending Message: "+$("#message").val());
            ws.send($("#message").val());
        });

      });
    </script>
  </head>

  <body>
    <h1>WebSockets Hello World</h1>
    <div id="connection_details">
      <label for="host">host:</label>
      <input type="text" id="host" value="localhost" style="background:#ff0000;"/><br />
      <label for="port">port:</label>
      <input type="text" id="port" value="8888" style="background:#ff0000;"/><br />
      <label for="uri">uri:</label>
      <input type="text" id="uri" value="/ws" style="background:#ff0000;"/><br />
      <input type="submit" id="open" value="open" />
    </div>
    <div id="message_details">
        </br></br>
        <label for="message">message:</label>
        <input type="text" id="message" value="Hello World!"/><br />
        <input type="submit" id="send" value="send" />
    </div>
    <div id="terminal">

    </div>
  </body>
</html>

2 个答案:

答案 0 :(得分:2)

您可以多次致电write_message

e.g。

def on_message(self, message):
    self.write_message("Message one")
    self.write_message("Message two")

答案 1 :(得分:0)

在您的代码上打开一个WebSocket,然后请求对此打开的WebSocket的多个响应。要获得多个回复,您可以按照Henry Heath的建议多次调用write_message

但是,如果您想要为多个WebSockets实现多个响应,可以按照以下方法进行操作。

clients = [] # list of opened WebSocket clients
class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        clients.append(self) # append a newly opened WebSocket client
        print 'new connection'

    def on_message(self, message):
        print 'message received:  %s' % message
        # loop over the opened WebSocket clients and send a message
        for client in clients:
            # Reverse Message and send it back
            print 'sending back message: %s' % message[::-1]
            client.write_message('%s' % (message[::-1]))

    def on_close(self):
        clients.remove(self) # remove a newly closed WebSocket client
        print 'connection closed'

    def check_origin(self, origin):
        return True

在您的模板(index.html)上,您只需单击打开按钮几次即可打开几个新的WebSock,然后单击按钮发送您将看到您将获得多个响应,与您打开的WebSocket的数量一样多。

这对于您需要向多个客户端广播消息的应用程序很方便,例如实时聊天。

另请务必检查official excellent Tornado documentation for WebSockets