Socket.IO Client Library in Python

Ada picture Ada · Jan 21, 2011 · Viewed 52k times · Source

Can anyone recommend a Socket.IO client library for Python? I've had a look around, but the only ones I can find are either server implementations, or depend on a framework such as Twisted.

I need a client library that has no dependencies on other frameworks.

Simply using one of the many connection types isn't sufficient, as the python client will need to work with multiple socketio servers, many of which won't support websockets, for example.

Answer

rmanna picture rmanna · Sep 28, 2011

Archie1986's answer was good but has become outdated with socketio updates (more specifically, its protocol : https://github.com/LearnBoost/socket.io-spec)... as far as i can tell, you need to perform the handshake manually before you can ask for a transport (e.g., websockets) connection... note that the code below is incomplete and insecure... for one, it ignores the list of supported transports returned in the handshake response and always tries to get a websocket... also it assumes that the handshake always succeeds... nevertheless, it's a good place to start

import websocket, httplib

...

'''
    connect to the socketio server

    1. perform the HTTP handshake
    2. open a websocket connection '''
def connect(self) :
    conn  = httplib.HTTPConnection('localhost:8124')
    conn.request('POST','/socket.io/1/')
    resp  = conn.getresponse() 
    hskey = resp.read().split(':')[0]

    self._ws = websocket.WebSocket(
                    'ws://localhost:8124/socket.io/1/websocket/'+hskey,
                    onopen   = self._onopen,
                    onmessage = self._onmessage)

....

you might also want to read up on python-websockets: https://github.com/mtah/python-websocket