gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:45:43 25 4
gpt4 key购买 nike

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

基于我在 GitHub 上找到的 Socket.io 引用资料,以及以下 WebSocket Python library .

这是我目前的代码:

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

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

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

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

最佳答案

我包裹了rodbarebones 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)

关于python - 格式化消息以从 python 客户端发送到 socket.io node.js 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6692908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com