Skip to content

Instantly share code, notes, and snippets.

@cd34
Forked from drewww/client.py
Created January 12, 2012 07:22
Show Gist options
  • Save cd34/1599221 to your computer and use it in GitHub Desktop.
Save cd34/1599221 to your computer and use it in GitHub Desktop.
Connect to socket.io server from python, using websocket
#!/usr/bin/env python
# encoding: utf-8
"""
client.py
Based heavily on:
- https://github.com/mtah/python-websocket/blob/master/examples/echo.py
- http://stackoverflow.com/a/7586302/316044
Created by Drew Harry on 2011-11-28.
Make sure you install python-websocket from github master:
easy_install -U https://github.com/mtah/python-websocket/tarball/master
and not the generic websocket
"""
import websocket, httplib, sys, asyncore
'''
connect to the socketio server
1. perform the HTTP handshake
2. open a websocket connection '''
def connect(server, port):
def _onopen():
print("opened!")
def _onmessage(msg):
print("msg: " + str(msg))
def _onclose():
print("closed!")
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)
if __name__ == '__main__':
if len(sys.argv) != 3:
sys.stderr.write('usage: %s <server> <port>\n' % \
sys.argv[0])
sys.exit(1)
server = sys.argv[1]
port = int(sys.argv[2])
connect(server, port)
try:
asyncore.loop()
except KeyboardInterrupt:
#ws.close() # ws isn't defined at this point
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment