从Python客户端向socket.io Node.js服务器发送消息的格式化方法

21 投票
2 回答
17529 浏览
提问于 2025-04-16 21:30

我正在尝试让一个Python客户端通过Socket.io 0.7与一个Node.js服务器进行通信,方法是向服务器发送一个自定义事件。

我参考了在GitHub上找到的Socket.io文档,以及以下的WebSocket Python库

到目前为止我的代码如下:

Node服务器

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()

Node控制台输出

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

现在看起来socket事件没有被触发,尽管服务器有回应ACK。所以消息是正确接收的,但我猜测格式可能不适合socket.io来触发事件。

我原以为不需要框架,但Archie1986在他的回答中似乎不同意这一点:Python中的Socket.IO客户端库

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

2 个回答

21

我把rod的研究整理成了一个简单的 socket.io 客户端库

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

解决了。我需要使用双引号。单引号在JSON中是不合法的。哎呀。

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

变成:

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

撰写回答