龙卷风的Websockets

时间:2016-03-04 16:06:33

标签: javascript python websocket tornado

我对龙卷风框架相对较新,到目前为止,事情一直很混乱,特别是在处理网络套接字时。到目前为止,我的代码看起来像这样:

import tornado.options
import tornado.web
import tornado.websocket
import tornado.ioloop

from tornado.options import options, define

define(name='port', default=8000, help='.', type=int)

class WSHandler(tornado.websocket.WebSocketHandler):
    clients = []

    def open(self):
        WSHandler.clients.append(self)
        self.write('client connected')

    def on_close(self):
        WSHandler.clients.remove(self)
        self.write('client removed')

    def on_message(self, message):
        for client in WSHandler.clients:
            WSHandler.client.write_message(message)

    def check_origin(self, origin):
        return True

if __name__ == '__main__':
    tornado.options.parse_command_line()
    application = tornado.web.Application(
        handlers=[
            (r'/webSocket', WSHandler),
        ],
    )
    application.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

,javascript文件看起来像这样



var ws = new WebSocket("ws://localhost:8000/webSocket")
ws.onopen = function() {
  ws.setData('Hello World');
};
ws.onmessage = function(evt) {
  ws.send(evt.data);
};




我目前正在阅读“龙卷风简介”这本书。并意识到某些事情现在已被弃用。我确实下载了git-hub上提供的演示,并尝试了解websocket演示。

我尝试创建一个简单的websocket应用程序,但它只是给我这个错误:

  

Can "Upgrade" only to "WebSocket"

另外,我还有另外一个关于龙卷风的问题
_()是什么意思?文档中给出的示例是

  

_("A person liked this", "%(num)d people liked this", len(people)) % {"num": len(people)}

这应该回归"一个人喜欢这个"如果人只有一个人我不太明白这是如何运作的

如果我犯了一个非常明显的错误,我道歉

1 个答案:

答案 0 :(得分:2)

我认为你可以看到tornado source,你可以找到以下内容:

# Upgrade header should be present and should be equal to WebSocket
    if self.request.headers.get("Upgrade", "").lower() != 'websocket':
        self.set_status(400)
        log_msg = "Can \"Upgrade\" only to \"WebSocket\"."
        self.finish(log_msg)
        gen_log.debug(log_msg)
        return

显然,HTML5 WebSocket协议是一种新协议。它实现了浏览器和服务器的全双工通信(全双工)。但是使用http只能制作单个社区。所以我建议你尝试另一个演示。

服务器:

    #!/usr/bin/python
#coding:utf-8
import os.path

import tornado.httpserver
import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpclient
import tornado.websocket

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

class SocketHandler(tornado.websocket.WebSocketHandler):
  """docstring for SocketHandler"""
  clients = set()

  @staticmethod
  def send_to_all(message):
      for c in SocketHandler.clients:
          c.write_message(json.dumps(message))

  def open(self):
      self.write_message(json.dumps({
          'type': 'sys',
          'message': 'Welcome to WebSocket',
      }))
      SocketHandler.send_to_all({
          'type': 'sys',
          'message': str(id(self)) + ' has joined',
      })
      SocketHandler.clients.add(self)

  def on_close(self):
      SocketHandler.clients.remove(self)
      SocketHandler.send_to_all({
          'type': 'sys',
          'message': str(id(self)) + ' has left',
      })

  def on_message(self, message):
    SocketHandler.send_to_all({
  'type': 'user',
  'id': id(self),
  'message': message,
        })

##MAIN
if __name__ == '__main__':
  app = tornado.web.Application(
    handlers=[
      (r"/", IndexHandler),
      (r"/chat", SocketHandler)
    ],
    debug = True,
    template_path = os.path.join(os.path.dirname(__file__), "templates"),
        static_path = os.path.join(os.path.dirname(__file__), "static")
  )
  app.listen(8000)
  tornado.ioloop.IOLoop.instance().start()

客户端:

    <html>
<head>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:8000/chat");
ws.onmessage = function(event) {
  console.log(event);
}
function send() {
  ws.send(document.getElementById('chat').value );
}
</script>
</head>

<body>
  <div>
    hello
    <input id="chat">
    <button  onclick="send()">send</button>
  </div>    
</body>
</html>