-1

I'm attempting to do the following:

  1. connect as client to an existing websocket
  2. process the streaming data received from this socket, and publish it on another websocket

I'm using twisted and autobahn to do so. I have managed to have the two parts working separately, by deriving a WebSocketClientProtocol for the client, and deriving an ApplicationSession in the second. The two run with the same reactor.

I am not sure however as to how to make them communicate. I would like to send a message on my server when the client receives a message, but I don't know how to get the running instance of the WebSocketClientProtocol...

Perhaps this isn't the right approach to do this either. What's the right way to do this?

Arthur B.
  • 3,445
  • 3
  • 21
  • 24

1 Answers1

0

I've been trying to solve similiar problem recently, here's what worked:

f = XLeagueBotFactory()
app =  Application(f)
reactor.connectTCP("irc.gamesurge.net", 6667, f)
reactor.listenTCP(port, app, interface=host)

^ This is in if __name__ == "__main__":

class Application(web.Application):
    def __init__(self, botfactory):
        self.botfactory = botfactory

Define the instance as self, then in my instance I was sending it to another handler for http post request (using cyclone)

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)

Now the important part comes in factory

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]

Finally in my client class:

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)

I'm not entirely sure that this code is perfect, or bugfree, but it should +- tell you how to deal with calling instance of protocol class. The problem afaik comes from name of instance protocol being generated inside of it's factory and not being sent elsewhere.

iScrE4m
  • 882
  • 1
  • 12
  • 31