gpt4 book ai didi

python - 使用 nodejs 作为服务器使用 Python 发出 socket.io 消息

转载 作者:可可西里 更新时间:2023-11-01 11:32:10 30 4
gpt4 key购买 nike

我需要一点帮助。

我正在进行测试以了解如何构建实时网络,因此我将 node.js 与 socket.io 结合使用。一切都很有趣,但如果我尝试在 channel 中发布一些消息,该 channel 正在监听 Node ,而来源不是 Node 或 javascript,它就会崩溃。

服务器端:(发送外部发布时失败的 Node )

var app = require('express')();
var http = require('http').Server(app);

var pub = require('redis').createClient(6379, 'localhost', {detect_buffers: true, return_buffers: false});
var sub = require('redis').createClient(6379, 'localhost', {return_buffers: true});

var io = require('socket.io')(http);

var redis = require('socket.io-redis');
io.adapter(redis({pubClient: pub, subClient: sub, host: '127.0.0.1', port: 6379}));


io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
console.log("something happens: " + msg);
});
});


http.listen(3000, function(){
console.log('listening on *:3000');
});

您不需要客户端代码来尝试,只需放置此代码并使用 node.js 运行即可。当它运行时,尝试直接在带有 Redis 的 channel 上发布,看看会发生什么。

Error: 5 trailing bytes
at Object.decode (.../node/node_modules/msgpack-js-v5/msgpack.js:266:47)
at Redis.onmessage (.../node/node_modules/socket.io-redis/index.js:93:24)
at emitTwo (events.js:87:13)
at RedisClient.emit (events.js:172:7)
at RedisClient.return_reply (.../node/node_modules/redis/index.js:654:22)
at .../node/node_modules/redis/index.js:307:18
at nextTickCallbackWith0Args (node.js:419:9)
at process._tickCallback (node.js:348:13)
enter code here

有人明白为什么会这样吗?我该如何解决?

谢谢!

新评论:感谢 robertklep,我知道它需要使用相同的协议(protocol),所以我使用它编写了一个简单的 Python 脚本,但它失败并出现相同的错误。

import redis
import msgpack
text_packed = msgpack.packb('refresh', use_bin_type=True)
r = redis.StrictRedis(host='localhost', port=6379, db=0)
r.publish('socket.io#/#', text_packed)

我也尝试过这种方法,我认为我传递了一些错误的参数:

from emitter import Emitter
io = Emitter(dict(host='localhost', port=6379))
io.Emit('chat message', "message from python!")
# or specificating the room
io.To("socket.io#/#").Emit('chat message', "message from python!")

在这种情况下,没有任何东西到达 redis。

最佳答案

socket.io-redis 使用 msgpack在 Redis 之上发布/订阅消息,因此您不能只将常规字符串推送到它并期望它工作。您使用的客户端需要使用相同的协议(protocol)。

关于python - 使用 nodejs 作为服务器使用 Python 发出 socket.io 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39232231/

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