2

I have implemented the follow class:

class WampServer(ApplicationSession):

    @inlineCallbacks
    def onJoin(self, details):
        self.connectedBoard = {}
        self.topic_connection = self.config.extra['topic_connection']
        self.topic_command = self.config.extra['topic_command']

        print("Session attached [Connect to WAMP Router]")

        def onMessage(*args):
            #DEBUG Message
            print args

            if args[1] == 'connection':
                self.connectedBoard[args[0]] = args[0]
                print self.connectedBoard

            if args[1] == 'disconnect':
                del self.connectedBoard[args[0]]
                print self.connectedBoard

        try:            
            yield self.subscribe(onMessage, self.topic_connection)
            print ("Subscribed to topic: "+self.topic_connection)

        except Exception as e:
            print("could not subscribe to topic:" +self.topic_connection)

Using another class for setting some configuration detail for connection, the class is shown follow:

class s4_wamp_server:
    def __init__(self, t_connection, t_command):
        self.topic_connection = t_connection
        self.topic_command = t_command

    def start(self):        
        self.runner = ApplicationRunner(url = urlWampRouter, realm = realmWampRouter, extra={'topic_connection':self.topic_connection, 'topic_command':self.topic_command}) 
        self.runner.run(WampServer)

I have the necessary to define a new method to publish a message in a specific topic like the follow:

...
...
def pubB(msg, topic):
        yield yelf.publish(topic,msg)
...
...

I would call this method after the "autobahn reactor" is started with the method s4_wamp_serv.stard().

----------------EDIT---------------------------

After some research I have implemented what I need for websocket protocol, the code is the follow:

# ----- twisted ----------
class _WebSocketClientProtocol(WebSocketClientProtocol):
    def __init__(self, factory):
        self.factory = factory

    def onOpen(self):
        #log.debug("Client connected")
        self.factory.protocol_instance = self
        self.factory.base_client._connected_event.set()

class _WebSocketClientFactory(WebSocketClientFactory):
    def __init__(self, *args, **kwargs):
        WebSocketClientFactory.__init__(self, *args, **kwargs)
        self.protocol_instance = None
        self.base_client = None

    def buildProtocol(self, addr):
        return _WebSocketClientProtocol(self)
# ------ end twisted -------
lass BaseWBClient(object):

    def __init__(self, websocket_settings):
        #self.settings = websocket_settings
        # instance to be set by the own factory
        self.factory = None
        # this event will be triggered on onOpen()
        self._connected_event = threading.Event()
        # queue to hold not yet dispatched messages
        self._send_queue = Queue.Queue()
        self._reactor_thread = None

    def connect(self):

        log.msg("Connecting to host:port")
        self.factory = _WebSocketClientFactory(
                                "ws://host:port",
                                debug=True)
        self.factory.base_client = self

        c = connectWS(self.factory)

        self._reactor_thread = threading.Thread(target=reactor.run,
                                               args=(False,))
        self._reactor_thread.daemon = True
        self._reactor_thread.start()

    def send_message(self, body):
        if not self._check_connection():
            return
        log.msg("Queing send")
        self._send_queue.put(body)
        reactor.callFromThread(self._dispatch)

    def _check_connection(self):
        if not self._connected_event.wait(timeout=10):
            log.err("Unable to connect to server")
            self.close()
            return False
        return True

    def _dispatch(self):
        log.msg("Dispatching")
        while True:
            try:
                body = self._send_queue.get(block=False)
            except Queue.Empty:
                break
            self.factory.protocol_instance.sendMessage(body)

    def close(self):
        reactor.callFromThread(reactor.stop)

import time
def Ppippo(coda):
        while True:
            coda.send_message('YOOOOOOOO')
            time.sleep(5)

if __name__ == '__main__':

    ws_setting = {'host':'', 'port':}

    client = BaseWBClient(ws_setting)

    t1 = threading.Thread(client.connect())
    t11 = threading.Thread(Ppippo(client))
    t11.start()
    t1.start()

The previous code work fine, but I need to translate this to operate on WAMP protocol insted websocket.

Does anyone know how I solve ?

Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
alotronto
  • 99
  • 2
  • 8
  • "I would call this method after the "autobahn reactor" is started with the method s4_wamp_serv.stard()." Where would you do that? Can you provide some example code where you publish event? – Raito Apr 12 '15 at 18:25

1 Answers1

0

You can put your publish at the bottom of the onJoin() method, it will fired once the client has connected to the router, hence way after the reactor has start:

class WampServer(ApplicationSession):

    @inlineCallbacks
    def onJoin(self, details):
        self.connectedBoard = {}
        self.topic_connection = self.config.extra['topic_connection']
        self.topic_command = self.config.extra['topic_command']

        print("Session attached [Connect to WAMP Router]")

        def onMessage(*args):
            #DEBUG Message
            print args

            if args[1] == 'connection':
                self.connectedBoard[args[0]] = args[0]
                print self.connectedBoard

            if args[1] == 'disconnect':
                del self.connectedBoard[args[0]]
                print self.connectedBoard

        try:            
            yield self.subscribe(onMessage, self.topic_connection)
            print ("Subscribed to topic: "+self.topic_connection)

        except Exception as e:
            print("could not subscribe to topic:" +self.topic_connection)

        yield self.pubB(your, args)

    def pubB(msg, topic):
        return self.publish(topic, msg)
Bite code
  • 578,959
  • 113
  • 301
  • 329