我正在尝试执行以下操作:
- 作为客户端连接到现有的websocket
- 处理从该套接字接收的流数据,并将其发布在另一个websocket上
我使用twisted和autobahn来实现这一点。通过为客户端派生WebSocketClientProtocol,并在第二个中派生ApplicationSession,我成功地使这两个部分分别工作。这两个反应堆在同一个反应堆中运行。
然而,我不确定如何让他们交流。我想在客户端收到消息时在服务器上发送消息,但我不知道如何获得WebSocketClientProtocol的运行实例。。。
也许这也不是正确的做法。做这件事的正确方法是什么?
我最近一直在尝试解决类似的问题,以下是行之有效的方法:
f = XLeagueBotFactory()
app = Application(f)
reactor.connectTCP("irc.gamesurge.net", 6667, f)
reactor.listenTCP(port, app, interface=host)
^这在if __name__ == "__main__":
中
class Application(web.Application):
def __init__(self, botfactory):
self.botfactory = botfactory
将实例定义为self,然后在我的实例中,我将其发送给另一个处理程序进行http post请求(使用旋风)
class requestvouch(web.RequestHandler):
def __init__(self, application, request, **kwargs):
super(requestvouch, self).__init__(application, request, **kwargs)
self.botfactory = application.botfactory
def msg(self, channel, msg):
bot = self.botfactory.getProtocolByName("XLeagueBot")
sendmsg(bot, channel, msg) # function that processed the msg through stuff like encoding and logging and then sent it to bot.msg() function that posts it to IRC (endpoint in my case)
def post(self):
msg = "What I'm sending to the protocol of the other thing"
self.msg("#xleague", msg)
现在重要的部分在工厂
class XLeagueBotFactory(protocol.ClientFactory):
protocol = XLeagueBot
def __init__(self):
self.protocols = {}
def getProtocolByName(self, name):
return self.protocols.get(name)
def registerProtocol(self, protocol):
self.protocols[protocol.nickname] = protocol
def unregisterProtocol(self, protocol):
del self.protocols[protocol.nickname]
最后在我的客户端类中:
class XLeagueBot(irc.IRCClient):
nickname = "XLeagueBot"
def connectionMade(self):
irc.IRCClient.connectionMade(self)
self.factory.registerProtocol(self)
def connectionLost(self, reason):
self.factory.unregisterProtocol(self)
irc.IRCClient.connectionLost(self, reason)
我不完全确定这段代码是否完美,或者是否没有错误,但它应该告诉您如何处理对协议类实例的调用。afaik的问题来自于实例协议的名称在其工厂内部生成,而没有发送到其他地方。