Using Python to communicate with web socket using JSON
<p>In order to better understand how websockets are used beyond the basic hello-world, I set myself the task of getting some data from a page using websockets and JSON (because the source code of gitxiv is readily available, I chose to look at <a href="http://gitxiv.com/day/2015/12/31" rel="noreferrer">http://gitxiv.com/day/2015/12/31</a>). </p>

<p>Connecting to this websocket via Python seems to be straightforward</p>

<pre><code>from websocket import create_connection
import websocket
import pprint

websocket.enableTrace(True)
ws=create_connection("ws://gitxiv.com/sockjs/212/2aczpiim/websocket")
result = ws.recv()
print "Received '%s'" % result
result = ws.recv()
print "Received '%s'" % result
</code></pre>

<p>I'm not entirely clear about the variables in the ws:// url, like '212'. Running this code seems to reliably connect (although it is always possible that failing to have the right variables in there causes the server to refuse to cooperate later?) </p>

<p>Now if I watch the communication between Firefox and the gitxiv page, I see that following connection of the websocket the server sends </p>

<pre><code>o
a["{\"server_id\":\"0\"}"]
</code></pre>

<p>The above script gets the same response, so it seems that the connection is successfully made.</p>

<p>However, this is where I stumble. The next step in the communication is that my browser sends quite a lot of information to the web service, such as the line:</p>

<pre><code>"["{\"msg\":\"connect\",\"version\":\"1\",\"support\":[\"1\",\"pre2\",\"pre1\"]}"]"
</code></pre>

<p>Sending these lines directly using ws.send() results in 'broken framing'. Sending just:</p>

<pre><code>controlstr='{"msg":"connect","version":"1","support":["1","pre2","pre1"]}';
ws.send(controlstr)
</code></pre>

<p>results in something being sent that looks like:</p>

<pre><code>send: '\x81\xbd\xef\x17F8\x945+K\x885|\x1a\x8cx(V\x8at2\x1a\xc350]\x9dd/W\x815|\x1a\xde5j\x1a\x9cb6H\x80e2\x1a\xd5Ld\t\xcd;dH\x9drt\x1a\xc356J\x8a&amp;de\x92'
</code></pre>

<p>I get a different error: </p>

<pre><code>'a["{\\"msg\\":\\"error\\",\\"reason\\":\\"Bad request\\"}"]'
</code></pre>

<p>It seems, therefore, that there is something wrong in the way that I am sending this JSON message to the websocket. Does anybody know what format it expects, and how to achieve it using websocket/websocket-client? Any clarification/suggestions would be most welcome. </p>

<p>The JSON messages I am looking to send are those that Firefox's Websocket developer tool reports: here is a screenshot:</p>

<p><a href="https://i.stack.imgur.com/mTG8X.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mTG8X.png" alt="Firefox Web Developer Tool report"></a></p>