Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Connect to server from python, using websocket
#!/usr/bin/env python
# encoding: utf-8
Based heavily on:
Created by Drew Harry on 2011-11-28.
import websocket, httplib, sys, asyncore
connect to the socketio server
1. perform the HTTP handshake
2. open a websocket connection '''
def connect(server, port):
print("connecting to: %s:%d" %(server, port))
conn = httplib.HTTPConnection(server + ":" + str(port))
resp = conn.getresponse()
hskey =':')[0]
ws = websocket.WebSocket(
onopen = _onopen,
onmessage = _onmessage,
onclose = _onclose)
return ws
def _onopen():
def _onmessage(msg):
print("msg: " + str(msg))
def _onclose():
if __name__ == '__main__':
if len(sys.argv) != 3:
sys.stderr.write('usage: python <server> <port>\n')
server = sys.argv[1]
port = int(sys.argv[2])
ws = connect(server, port)
except KeyboardInterrupt:

Thanks for this!

As a note:

The httplib module has been renamed to http.client in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment