2016-08-30 133 views
0

我需要一些幫助。使用nodejs作爲服務器使用Python發送socket.io消息

我正在做測試,以瞭解如何構建一個實時網站,所以我使用node.js與socket.io。所有的作品都很有趣,但是如果我嘗試在通道中發佈一些消息,而這些消息是使用不是節點或JavaScript的不同源的偵聽節點,則會崩潰。

服務器端:(節點,當外部發布的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'); 
}); 

你並不需要嘗試的客戶端代碼,只是把這個代碼,並與節點運行它。當它運行時,嘗試直接在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) 

我也嘗試過這種方法,我覺得我通過一些PARAM錯誤:

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的。

回答

0

socket.io-redis在Redis之上使用msgpack發佈/發送消息,因此您不能只是將常規字符串推送到發佈/訂閱消息,並期望它能夠正常工作。您使用的客戶端需要使用相同的協議。

+0

感謝那些信息Robertklep。我使用msgpack通過redis創建了一個Python腳本,但它不能解決問題。 我有同樣的錯誤:「錯誤:23尾隨字節」。 – user2742735

相關問題