简体   繁体   中英

Emit socket.io message with Python using nodejs as server

I need a bit of help.

I'm doing tests to learn how to build a realtime web, so I use node.js with socket.io. All works fun but if I try to publish some message in the channel that is listening node with a different source that isn't node or javascript it crashes.

Server side: (node that fails when a external publish is sended)

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');
});

You don't need the client-side code for try it, just put this code and run it with node. When it is running, try to publish on the channel with Redis directly and see whats happens.

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

Somebody understands why this happen? How can I fix it?

Thank you!

NEW COMMENT: Thanks to robertklep I know that it need to use the same protocol, so I wrote a simple Python script using it, but it fails with the same error.

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)

I also tried this approach, I think Im passing some param wrong:

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!")

In this case, nothing arrives to redis.

socket.io-redis uses msgpack on top of Redis to pub/sub messages, so you can't just push regular strings to it and expect it to work. The client you're using needs to be talking the same protocol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM