gpt4 book ai didi

python - 在单个高速公路 WebSocketProtocol 中使用不同的函数处理消息

转载 作者:行者123 更新时间:2023-11-30 23:33:40 25 4
gpt4 key购买 nike

我对 websockets 还很陌生,一直在尝试将 python 与 autobahn 和twisted 一起使用来连接到多个套接字,然后对来自每个不同套接字的数据执行不同的操作。

最终我将拥有 3 到 4 个不同的处理函数和最多 10-15 个 Websocket 连接。

我想将一个函数传递到协议(protocol)中以用于分析返回的数据。我遇到的问题是我能找到访问 WebSocketClientProtocol 的“onMessage()”方法中的函数的唯一方法,该方法是为类而不是实际对象设置的,所以我只能使用一个数据处理函数适用于所有网络套接字。

下面的代码示例。

from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol
from twisted.internet import reactor, ssl

# message processing methods
def method1(self, data):
print 'Using Method 1.'

def method2(self, data):
print 'Using Method 2.'

# factory and protocol classes
class myFactory(WebSocketClientFactory):
def clientConnectionLost(self, connector, reason):
connector.connect()

class myWS(WebSocketClientProtocol):

def initialize(self, url, data_fcn):
self.factory = myFactory(url)
self.factory.protocol = myWS

# !!! set in class, not object !!!
self.factory.protocol.data_fcn = data_fcn

def onMessage(self, msg, binary):
self.data_fcn(msg)

def onClose(self, a, b, c):
reactor.stop()
reactor.disconnectAll()

def kill(self):
self.transport.loseConnection()
reactor.stop()
reactor.disconnectAll()


if __name__ == '__main__':

# websocket topics unique
topic_ids = [ '3395',
'3563',
'3562' ]

# data processing functions can repeat
data_process_fcns = [ method1,
method2,
method1 ]

for topic, func in zip(topic_ids, data_process_fcns):

url = 'wss://mywebsocket.com/feed?topic_id[]=' + topic
ws = myWS()
ws.initialize(url, func)

reactor.connectSSL(ws.factory.host, ws.factory.port, ws.factory, ssl.ClientContextFactory())

reactor.run()

我当前的解决方案是为我想要使用的每个数据处理函数创建一个类。所以,对于方法1我有

class myWS_method1(WebSocketClientProtocol):

    def onMessage(self, msg, binary):
method1(msg)

以及我想要使用的每种数据处理方法的类似类。

希望找到一个更优雅的解决方案,让我能够重用单个类。

谢谢

最佳答案

在 Twisted 中,你几乎不需要自己构建协议(protocol),这是工厂的责任。我想要这样的东西:

class myFactory(WebSocketClientFactory):

def __init__(self, url, data_processing):
WebSocketClientFactory.__init__(self, url)
# here you could have passed whatever parameters
# later allow you to build up the protocol instance
self._data_processing = data_processing

def buildProtocol(self, addr):
# Use this method to control the creation of the
# protocol instance.
# You can either build a protocol here and inject
# data_func, or use different protocol class type.

protocol = myWs()
protocol.data_func = self._data_processing
return protocol

然后,带有连接的循环将如下所示:

for topic, func in zip(topic_ids, data_process_fcns):
url = 'wss://mywebsocket.com/feed?topic_id[]=' + topic
factory = myFactory(url, func)
reactor.connectSSL(factory.host, factory.port, factory, ssl.ClientContextFactory())

关于python - 在单个高速公路 WebSocketProtocol 中使用不同的函数处理消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18625385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com