emit()不工作[Node.js]

时间:2015-07-24 21:31:04

标签: javascript php node.js redis laravel-5

我对laravel 5事件[channal] update.group进行了subcibe,我在触发事件后在控制台中重新发送消息但在浏览器的客户端我没有收到任何消息。此外,在我触发事件后,我在控制台中重新发送消息,然后节点服务器停止使用消息:

bash-4.2# node node.js
Listening on Port 3000
Message Recieved: testasdsa
/home/client/public_html/node_modules/ioredis/lib/parsers/javascript.js:216
        throw err;
              ^
SyntaxError: Unexpected token e
    at Object.parse (native)
    at Redis.<anonymous> (/home/client/public_html/node_modules/node.js:10:20)
    at Redis.emit (events.js:110:17)
    at Redis.exports.returnReply (/home/client/public_html/node_modules/ioredis/lib/redis/parser.js:79:16)
    at ReplyParser.<anonymous> (/home/client/public_html/node_modules/ioredis/lib/redis/parser.js:27:10)
    at ReplyParser.emit (events.js:107:17)
    at ReplyParser.send_reply (/home/client/public_html/node_modules/ioredis/lib/parsers/javascript.js:281:8)
    at ReplyParser.execute (/home/client/public_html/node_modules/ioredis/lib/parsers/javascript.js:210:14)
    at Socket.<anonymous> (/home/client/public_html/node_modules/ioredis/lib/redis/event_handler.js:90:22)
    at Socket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at Socket.Readable.push (_stream_readable.js:126:10)
    at TCP.onread (net.js:538:20)

这是我的node.js文件:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('update.group', function(err, count) {
});
redis.on('message', function(channel, message) {
    console.log('Message Recieved: ' + message);
    message = JSON.parse(message);
    io.sockets.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function(){
    console.log('Listening on Port 3000');
});

对于客户方:

    var socket = io.connect('127.0.0.1:3000');
    socket.on("update.group", function(message){
    // increase the power everytime we load test route
    console.log(message);
});

任何人都可以找到问题所在?

1 个答案:

答案 0 :(得分:2)

从您的调试输出中可以看出这一点:testasdsa是无效的JSON,因此您无法解析它。您需要更改发布消息的代码,以便正确地进行JSON编码。

由于您希望对象上有eventdata属性,因此发布商需要编写类似{ "event": "foo", "data": "testasdsa" }的内容。

要解决浏览器客户端无法获取事件的问题,您需要在服务器脚本中更改此问题:

io.sockets.emit(channel + ':' + message.event, message.data);

为:

io.sockets.emit(message.event, message.data);

然后确保发布商发送类似{ "event": "update.group", "data": "somedata" }

的内容