TypeError:无法调用未定义的方法'emit'

时间:2013-01-11 19:06:19

标签: node.js socket.io

当我尝试运行我的nodejs应用程序时,我遇到错误。我正在制作聊天应用。 这是我的代码:

var users = {};
var sockets = {};
var connect = require('connect');
var io = require('socket.io');

var fs = require('fs');

var port = process.env.VCAP_APP_PORT || process.env['app.port'] || 3000;

var app = connect().use(connect.static('public')).listen(port);

var chat_room = io.listen(app);

chat_room.sockets.on('connection', function(socket) {

    socket.emit('entrance', {message: 'Welcome to the chat room!'});
    // Register your client with the server, providing your username
    socket.on('init', function(username) {
        users[username] = socket.id;    // Store a reference to your socket ID
        sockets[socket.id] = { username : username, socket : socket };  // Store a reference to your socket

    });

    socket.on('chat', function(data) {

        user = data.message.user;
        message = data.message.message;

        chat_room.sockets[users[user]].emit(
            'chat', 
            { 
                message : message,
                from : sockets[socket.id].username
            }
        );
    });
});

完整错误:

> TypeError: Cannot call method 'emit' of undefined
>     at Socket.<anonymous> (C:\Users\Niraj\Desktop\node\private-chat\app.js:35:40)
>     at Socket.EventEmitter.emit [as $emit] (events.js:96:17)
>     at SocketNamespace.handlePacket (C:\Users\Niraj\Desktop\node\private-chat\node_modules\socket.io\lib\namespace.js:335:22)
>     at Manager.onClientMessage (C:\Users\Niraj\Desktop\node\private-chat\node_modules\socket.io\lib\manager.js:487:38)
>     at WebSocket.Transport.onMessage (C:\Users\Niraj\Desktop\node\private-chat\node_modules\socket.io\lib\transport.js:387:20)
>     at Parser.<anonymous> (C:\Users\Niraj\Desktop\node\private-chat\node_modules\socket.io\lib\transports\websocket\hybi-16.js:39:10)
>     at Parser.EventEmitter.emit (events.js:96:17)
>     at opcodeHandlers.1.finish (C:\Users\Niraj\Desktop\node\private-chat\node_modules\socket.io\lib\transports\websocket\hybi-16.js:288:16)
>     at Parser.opcodeHandlers.1.expectData [as expectHandler] (C:\Users\Niraj\Desktop\node\private-chat\node_modules\socket.io\lib\transports\websocket\hybi-16.js:299:15)
>     at Parser.add (C:\Users\Niraj\Desktop\node\private-chat\node_modules\socket.io\lib\transports\websocket\hybi-16.js:466:24)

我只是nodejs的初学者,我的代码有问题吗?提前致谢

2 个答案:

答案 0 :(得分:0)

您正在尝试向未识别的套接字发送消息。

不知道你的应用程序的其余部分,但是:

user = data.message.user;

你不应该调用“data.message.username”而不是“data.message.user”吗?可能是不同的事情。

答案 1 :(得分:-1)

不进行发光,而是进行广播:

socket.broadcast.emit(msg)