0

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の初心者ですが、コードに何か問題がありますか?前もって感謝します

4

2 に答える 2

0

You are trying to send a message to an unidentified socket.

Don't know the rest of your application, but on:

user = data.message.user;

shouldn't you be calling "data.message.username" instead of "data.message.user"? Could be different things.

于 2013-04-01T15:14:47.820 に答える
-1

放出する代わりに、ブロードキャストを実行します。

socket.broadcast.emit(msg)
于 2013-01-11T19:12:36.490 に答える