格式化消息以从python客户端发送到socket.io node.js服务器

时间:2011-07-14 12:11:10

标签: python node.js websocket socket.io

我正在尝试通过向服务器发送自定义事件,使用Socket.io 0.7让Python客户端与Node.js服务器通信。

基于我在GitHub和以下WebSocket Python library找到的Socket.io引用。

到目前为止,这是我的代码:

节点服务器

io.sockets.on('connection', function (socket) {
  socket.on('newimg', function(data) {
        console.log(data);
  });
});

Python客户端

def handshake(host, port):
    u = urlopen("http://%s:%d/socket.io/1/" % (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)
        else:
            raise TransportException()
    else:
        raise InvalidResponseException()


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

节点控制台输出

debug - client authorized
info  - handshake authorized 12738935571241622933
debug - setting request GET /socket.io/1/websocket/12738935571241622933
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控制台输出

Done
1::
6:::1
Closing connection

现在看来套接字事件没有被触发,尽管服务器用ACK响应。所以消息正在被正确接收,但我假设,没有正确格式化socket.io来触发事件。

我不认为框架是必要的,但Archie1986似乎不同意他对此的回应:Socket.IO Client Library in Python

我可能在这里做错了什么?

2 个答案:

答案 0 :(得分:20)

我将rod的研究结果编入barebones socket.io client library

pip install -U socketIO-client
python
    from socketIO_client import SocketIO
    with SocketIO('localhost', 8000) as socketIO:
        socketIO.emit('aaa')
        socketIO.wait(seconds=1)

答案 1 :(得分:14)

解决。我需要使用双引号。单引号不是有效的JSON。 Woops。

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

变为:

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