私は websockets にかなり慣れていないので、autobahn と twisted で python を使用して複数のソケットに接続し、各ソケットからのデータに対してさまざまなアクションを実行しようとしています。
最終的に、3 ~ 4 個の異なる処理機能と、合計で最大 10 ~ 15 個の Websocket 接続を持つことになります。
戻ってくるデータを分析するために使用する関数をプロトコルに渡したいと思います。私が抱えている問題は、WebSocketClientProtocol の「onMessage()」メソッドの関数にアクセスする唯一の方法であり、実際のオブジェクトではなくクラスに設定されているため、1 つのデータ処理関数で立ち往生しています。すべての WebSocket 用。
以下のコード例。
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 つのクラスを作成することです。だから、私が持っているmethod1について
class myWS_method1(WebSocketClientProtocol):
と
def onMessage(self, msg, binary):
method1(msg)
使用したい各データ処理方法の同様のクラス。
単一のクラスを再利用できる、より洗練されたソリューションを見つけたいと思っていました。
ありがとう、