nodejs上的通信 - socket.eon没有正确捕获socket.emit

时间:2014-02-27 11:10:24

标签: node.js socket.io

我目前遇到Node JS的问题,尝试与会话身份验证进行非常简单的聊天。 验证是正常的,但socket.emit事件(服务器端)未被socket.on事件(客户端)捕获。 这里的代码。 文件app.js:

app.get('/chat', [requireLogin], require('./lib/chat.js').chat(io));

文件lib / chat.js:

exports.chat = function(io){
    return function(req,res) {
        res.render('chat');

        var ent = require('ent'); // same as htmlentities for PHP

        io.sockets.on('connection', function (socket) {
            var username = ent.encode(socket.handshake.username);

            console.log('first_connection:'+username);
            socket.emit('first_connection', username);

            socket.on('connect_success', function() {
                console.log('connect_success:'+username);
                socket.broadcast.emit('join', username);
            });
        });
    }
};

和客户方:

var sio = io.connect(), socket = sio.socket.of('/chat');

socket.on('first_connection', function (pseudo) {
    console.log('first_connection is caught. Pseudo:'+pseudo);
    document.title = pseudo + ' - ' + document.title;
    socket.emit('connect_success');
});

我在客户端没有登录,登录服务器端:

first_connection:Test
   debug - websocket writing 5:::{"name":"first_connection","args":["Test"]}

[编辑]以下是我的app.js文件中IO套接字的声明:

const
    express = require('express'),
    path = require('path'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    fs = require('fs'),
    connect = require('express/node_modules/connect'),
    cookie = require('express/node_modules/cookie')
;

1 个答案:

答案 0 :(得分:0)

好的,我一步一步地回去重做同样的事情,现在效果很好! 我认为我的问题来自于我忘记了模块cookie的安装。

非常感谢! :)