Using Python to communicate with web socket using JSON Using Python to communicate with web socket using JSON json json

Using Python to communicate with web socket using JSON


If you look closely at what what's sent through the browser, notice that it's:

["{\"msg\":\"connect\"}"]

This looks an awful lot like an array of JSON strings. Indeed, if you try to replicate it:

ws.send(json.dumps([json.dumps({'msg': 'connect', 'version': '1', 'support': ['1', 'pre2', 'pre1']})]))

You'll see that you get connected. Here's my entire code:

import jsonimport pprintimport websocketfrom websocket import create_connectionwebsocket.enableTrace(True)ws = create_connection('ws://gitxiv.com/sockjs/212/2aczpiim/websocket')result = ws.recv()print('Result: {}'.format(result))result = ws.recv()print('Result: {}'.format(result))ws.send(json.dumps([json.dumps({'msg': 'connect', 'version': '1', 'support': ['1', 'pre2', 'pre1']})]))result = ws.recv()print('Result: {}'.format(result))