rod rod - 1 year ago 141
Node.js Question

Formatting messages to send to node.js server from python client

I'm trying to get a Python client talking to a Node.js server using 0.7, by sending a custom event to the server.

Based on the reference I have found on GitHub, and the following WebSocket Python library.

Here's is my code so far:

Node server

io.sockets.on('connection', function (socket) {
socket.on('newimg', function(data) {

Python client

def handshake(host, port):
u = urlopen("http://%s:%d/" % (host, port))
if u.getcode() == 200:
response = u.readline()
(sid, hbtimeout, ctimeout, supported) = response.split(":")
supportedlist = supported.split(",")
if "websocket" in supportedlist:
return (sid, hbtimeout, ctimeout)
raise TransportException()
raise InvalidResponseException()

(sid, hbtimeout, ctimeout) = handshake(HOSTNAME, PORT) #handshaking according to spec.
Except Exception as e:
print e
ws = websocket.create_connection("ws://%s:%d/" % (HOSTNAME, PORT, sid))
print ws.recv()
ws.send("5:1::{'name':'newimg', 'args':'bla'}")
print ws.recv()
print "Closing connection"

Node console output

debug - client authorized
info - handshake authorized 12738935571241622933
debug - setting request GET /
debug - set heartbeat interval for client 12738935571241622933
debug - client authorized for
debug - websocket writing 1::
debug - websocket received data packet 2::
debug - got heartbeat packet
debug - websocket received data packet 5:1::{'name':'newimg', 'args':'bla'}
debug - acknowledging packet automatically
debug - websocket writing 6:::1
info - transport end
debug - set close timeout for client 12738935571241622933
debug - cleared close timeout for client 12738935571241622933
debug - cleared heartbeat interval for client 12738935571241622933
debug - discarding transport

Python console output

Closing connection

Now it seems the socket event is not being triggered, despite the server responding with ACK. So the message is being correctly received but I am assuming, not formatted properly for to trigger an event.

I didn't think framing was necessary, however Archie1986 seems to disagree on his response to this: Socket.IO Client Library in Python

What might I be doing wrong here?

rod rod
Answer Source

Resolved. I needed to use double quotes. Single quotes are not valid JSON. Woops.

ws.send("5:1::{'name':'newimg', 'args':'bla'}")


ws.send('5:1::{"name":"newimg", "args":"bla"}')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download