Skip to content

Instantly share code, notes, and snippets.

@ryanchang
Last active September 7, 2015 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanchang/9a8ee4eafb79b4cda4eb to your computer and use it in GitHub Desktop.
Save ryanchang/9a8ee4eafb79b4cda4eb to your computer and use it in GitHub Desktop.
Python client for websocket_rails.
import websocket
import thread
import time
import json
def on_message(ws, message):
print "recieved: " + message
response = json.loads(message)[0]
event = response[0]
print "event: " + event
if event == 'websocket_rails.channel_token':
channel_token = response[1]["data"]["token"]
print "channel_token: " + channel_token
#TODO: handle ping request here.
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
def on_open(ws):
def run(*args):
time.sleep(1)
#subscribe("TestDev")
channel = "TestDev"
ws.send('["websocket_rails.subscribe", {"data": {"channel": "%s"}}]' % channel)
ws.send('["device.event", {"data": {"id": 1, "weight": 70.0, "temperature": 30.0, "humidity": 60.0}}]')
thread.start_new_thread(run, ())
def subscribe(channel):
ws.send('["websocket_rails.subscribe", {"channel": "%s"}]' % channel)
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://civilizationdata.com:7000/websocket",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
@ryanchang
Copy link
Author

  • Client -> Server without channel
["new_message",{"text":"Hello","username":"ryan.chang"},{"id":83699}]
  • Server -> Client without channel
["new_message",{"user":"ryan.chang","text":"Hello"},{"id":null,"channel":null,"user_id":null,"success":null,"result":null,"token":null,"server_token":null}]
  • Client subscribe to channel
["websocket_rails.subscribe",{"id":93653,"data":{"channel":"TestDev"}}]
  • Server send channel token to client
[["websocket_rails.channel_token",{"id":null,"channel":"TestDev","user_id":null,"data":{"token":"900bf48e-2b5e-4df8-9b5c-49783068a9a9"},"success":null,"result":null,"token":null,"server_token":null}]]
  • Client send to a specific channel
["device.event",{"id":84869,"channel":"TestDev","data":{"id":1},"token":"900bf48e-2b5e-4df8-9b5c-49783068a9a9"}]
  • Ping
[["websocket_rails.ping",{"id":null,"channel":null,"user_id":null,"data":{},"success":null,"result":null,"token":null,"server_token":null}]]
  • Pong
["websocket_rails.pong",{"id":119902,"data":{}}]

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