Search code examples
pythonpython-2.7autobahn

How to obtain the client IP address in Autobahn Wamp Protocol?


I am using the Autobahn Wamp for socket connection in Python. I am using the PubSub mechanism for establishing the connection. The connection is established successfully.

But I cannot find a way to maintain the list of connected clients with the server.

Please any one can suggest a way with the help of which I can maintain a list of IP addresses of the connected clients and a way in which I can send reply to specific clients using the respective address?

Please reply as early as possible.

Thanks in advance


Solution

  • This is a two part question. Part one is asking how to identify the ip address for connected web sockets. Part two is asking how to direct a message to a particular session. I'll start with part two. In the comment above there is a factory variable. That can be used anywhere it is in scope like this:

    factory.dispatch("http://domain.com/topic", "payload", [ excluded sessions ], [ included sessions])
    

    A session id looks like this TB15LhO8oS0MLsj6 and is available to the methods in the protocol, like the onSessionOpen, onClose, in the self.session_id variable. I do something like this :

    ses_var = {} 
    

    Put this in the top of your code, a global variable. Then, in the onSessionOpen():

    def onSessionOpen(self):
        global ses_var
    
        ses_var[self.session_id] = self
        print "connection from ", self.peer.host, self.peer.port
    

    This code gives you a handle on the session. You will need to manage this variable, and remove the session from the variable in the onClose() method.

    So, if you have captured all of the open sessions in the ses_var variable then you could publish messages to any (and all) of them using the dispatch, again:

        factory.dispatch("http://domain.com/topic", "payload", [],
          factory.sessionIdsToProtos(ses_var.keys()))
    

    Note that the session_id is NOT the argument expected, you have to convert the id to the actual session object.

    The two arrays in factory.dispatch define who not to send the message to, and who to send the message to. If you pass None as the second array, you will send a message to all clients, so the dispatch for the example could be rewritten as:

        factory.dispatch("http://domain.com/topic", "payload", [], None)
    

    If you want to send it to the first session (for example), you could do:

        factory.dispatch("http://domain.com/topic", "payload", [],
             factory.sessionIdsToProtos([ses_var[0].session_id]))