0

为龙卷风 websocket 服务器提供这个简单的 python 代码。

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import time
import os
import subprocess
from subprocess import *
import datetime

listeners = []


class WSHandler(tornado.websocket.WebSocketHandler):

  def open(self):
    print 'New connection was opened'
    self.write_message("Con!")
    listeners.append(self)


  def on_message(self, message):
    print 'Received:', message
    self.write_message("Received: " + message)
    for w in listeners:
        w.write_message('MASS MESSAGE')

  def on_close(self):
    print 'Con closed...'


  def trimite(self, msg):
    self.write_message(msg)


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

if __name__ == "__main__":
  http_server = tornado.httpserver.HTTPServer(application)
  http_server.listen(65)
  tornado.ioloop.IOLoop.instance().start()

每次我从网页执行命令到 websocket 服务器时,都会向所有连接发送一条消息。它工作正常...但是,如果我关闭并重新连接客户端并尝试发送另一个命令,我会收到此错误,并且连接关闭。我必须重新启动 websocket 服务器才能让它再次工作。知道为什么吗?谢谢!

ERROR:root:Uncaught exception in /ws
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/tornado/websocket.py", line 258, in wrapper
    return callback(*args, **kwargs)
  File "ciuciu.py", line 26, in on_message
    w.write_message('MASS MESSAGE')
  File "/usr/lib/python2.7/dist-packages/tornado/websocket.py", line 144, in write_message
    self.ws_connection.write_message(message, binary=binary)
AttributeError: 'NoneType' object has no attribute 'write_message'
4

1 回答 1

0

好的,想通了。我必须添加 listeners.remove:

  def on_close(self):
    listeners.remove(self)
    print 'Con closed...'
于 2013-09-02T10:56:02.667 回答