【问题标题】:Emit socket.io message with Python using nodejs as server使用 nodejs 作为服务器使用 Python 发出 socket.io 消息
【发布时间】:2017-01-07 00:26:26
【问题描述】:

我需要一点帮助。

我正在进行测试以了解如何构建实时网络,因此我将 node.js 与 socket.io 结合使用。一切都很有趣,但是如果我尝试在侦听节点的频道中发布一些消息,并且使用不同的源(不是节点或 javascript)它会崩溃。

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

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 在频道上发布,看看会发生什么。

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,我知道它需要使用相同的协议,所以我使用它编写了一个简单的 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。

【问题讨论】:

    标签: python node.js redis socket.io msgpack


    【解决方案1】:

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

    【讨论】:

    • 感谢 Robertklep 提供的信息。我通过 redis 使用 msgpack 使用 Python 创建了一个新脚本,但它不能解决问题。我有同样的错误:“错误:23 个尾随字节”。
    猜你喜欢
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多