Skip to main content
 首页 » 编程设计

python之使用全局变量的 WebSocket 线程

2025年05月04日34jiqing9006

我正在尝试使用非常流行的 Tornado server for Python 创建一个 WebSocket 服务器,但我在创建全局范围的 self 变量以便将数据写入类外的网络套接字时遇到问题。

This answer完全解决了我的问题,但我想更进一步,将整个问题包装在一个线程中。

这是我的套接字:

wss = [] 
 
class WSHandler(tornado.websocket.WebSocketHandler): 
 
    def check_origin(self, origin): 
        return True 
 
    def open(self): 
        print ('New connection established.') 
        if self not in wss: 
            wss.append(self) 
 
    def on_message(self, message): 
        print ('Received message: %s' % message) 
 
    def on_close(self): 
        print ('Connection closed.') 
        if self in wss: 
            wss.remove(self) 

这是写入套接字的类之外的方法:

def write_data(message): 
    for ws in wss: 
        print ("Sending: %s" % message) 
        ws.write_message(message); 

这是线程服务器类:

class ServerThread(threading.Thread): 
 
    def run(self): 
        print ("Starting server.") 
        http_server = tornado.httpserver.HTTPServer(application) 
        http_server.listen(4045) 
        main_loop = tornado.ioloop.IOLoop.instance() 
        main_loop.start() 
 
    def send_data(self, message): 
        write_data(message); 

奇怪的是,当代码没有包装在Thread 类中时,write 方法工作正常。在上面的代码中,当我调用时:

server_thread = ServerThread() 
server_thread.start() 
server_thread.send_data("Ping!") 

没有任何反应。方法write_data(message)进入了,但是显然wss[]是空的。

如果您能提供任何帮助,我们将不胜感激!

更新:

我一直在研究这个问题,但无济于事。另一件奇怪的事情:已建立新连接。 从不打印到控制台,这让我认为套接字从未附加到列表中,而不是它是一个变量作用域问题。

请您参考如下方法:

您不应将端口 4045 用于 HTTP/WebSocket 服务,因为它已被浏览器阻止。您可能会从浏览器收到一条错误消息:

Failed to construct 'WebSocket': The port 4045 is not allowed. 

http://www-archive.mozilla.org/projects/netlib/PortBanning.html http://support.apple.com/en-us/HT203772