Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python-websocket and socket.io namespace

I would write a websocket client in python to connect to a server written with socket.io. My current code, taken from 1 is the following:

import websocket, httplib, sys, asyncore
def connect(server, port):

    print("connecting to: %s:%d" %(server, port))

    conn  = httplib.HTTPConnection(server + ":" + str(port))
    conn.request('POST','/socket.io/1/')
    resp  = conn.getresponse() 
    hskey = resp.read().split(':')[0]
    ws = websocket.WebSocket(
                'ws://'+server+':'+str(port)+'/socket.io/1/websocket/'+hskey,
                onopen   = _onopen,
                onmessage = _onmessage,
                onclose = _onclose)

    return ws

def _onopen():
    print("opened!")

def _onmessage(msg):
    print("msg: " + str(msg))

def _onclose():
    print("closed!")


if __name__ == '__main__':

    server = 'localhost'
    port = 8081

    ws = connect(server, port)

    try:
        asyncore.loop()
    except KeyboardInterrupt:
        ws.close()

My question is how do I connect to a specific namespace?

Thanks

like image 266
Emanuele Avatar asked Sep 22 '26 18:09

Emanuele


1 Answers

You can use socketIO-client which is available on PyPI under the MIT license. It has support for different namespaces of a single socket.

from socketIO_client import SocketIO, BaseNamespace

class MainNamespace(BaseNamespace):

    def on_aaa(self, *args):
        print 'aaa', args

class ChatNamespace(BaseNamespace):

    def on_bbb(self, *args):
        print 'bbb', args

class NewsNamespace(BaseNamespace):

    def on_ccc(self, *args):
        print 'ccc', args

mainSocket = SocketIO('localhost', 8000, MainNamespace)
chatSocket = mainSocket.connect('/chat', ChatNamespace)
newsSocket = mainSocket.connect('/news', NewsNamespace)
mainSocket.wait()
like image 94
Roy Hyunjin Han Avatar answered Sep 25 '26 06:09

Roy Hyunjin Han