Skip to main content
 首页 » 编程设计

Python Twisted之如何通过已连接的套接字连接发送数据

2025年02月15日10exmyth

我有一个服务器如下:-

class MyServerProtocol(WebSocketServerProtocol): 
 
    def onConnect(self, request): 
        print("Client connecting: {0}".format(request.peer)) 
 
    def onOpen(self): 
        print("WebSocket connection open.") 
 
    def onMessage(self, payload, isBinary): 
        self.sendMessage(payload, isBinary) 
 
    def onClose(self, wasClean, code, reason): 
        print("WebSocket connection closed: {0}".format(reason)) 

上面的代码接收消息并用相同的消息回复。但是,我的用例不同。

我正在处理一些数据,将其存储到数据库中,然后最终想将数据发送到连接的客户端,或者将一种类型的数据发送到特定的一组连接的客户端,将另一种类型的数据发送到另一种。

我该怎么做?如何在类外调用 sendMessage 函数?

请您参考如下方法:

您需要子类化 WebSocketServerFactory 以跟踪您的连接。

看看这个example ,它将所有打开的连接存储在一个列表中并向所有连接广播。您可以轻松调整它以向特定客户端发送特定消息。