在Node.JS中获取调用emit的错误

时间:2015-01-26 23:17:02

标签: javascript node.js

我正在编写一个私人聊天示例,在开发过程中,我收到一个错误,称为emit 以下代码:

sockets[users[to]].emit('updateChat' , {user : sockets[socket.id].username , mess : Msg});

。 产生这个错误:

Object #(Object) has no method 'emit'

我的所有代码:

var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
server.listen(8080);
var usernames = {};
var rooms     = {};
var username  = '';
var users     = {};
var sockets   = {};

app.get('/' ,function (req , res){
res.sendfile(_dirname + '/test.html');
});

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

socket.on('adduser' , function (username){
    if(username == '')
        username = 'guest';
    else
        socket.username = username ; 
    usernames[username] = username;

    users[username] = socket.id;
    sockets[socket.id] = {username : username  , socket : socket};
    //console.log(users);
    socket.emit('updateChat','SERVER', username +  ' has connect');
    socket.broadcast.emit('updateChat' , 'SERVER', username + ' has connect');
    socket.emit('listUser' ,usernames, username);
    socket.broadcast.emit('listUser' , usernames ,username);
});

socket.on('sendchat', function(data){
    io.sockets.in(socket.room).emit('updateChat' , socket.username , data);
    //sockets[socket.id]= { username : socket.username , data : data , socket : socket};
});

socket.on('room', function (newRoom){
    //console.log(socket.room);
    rooms[newRoom] = newRoom;
    console.log(rooms);
    //socket.leave(socket.room);
    if(socket.room)
    {   
        socket.leave(socket.room);
        socket.broadcast.to(socket.room).emit('updateChat' , 'SERVER' , socket.username + 'has left the room');
    }
    socket.join(newRoom);
    socket.room = newRoom ;
    socket.emit('updateChat' ,'SERVER','connected');            
    socket.broadcast.to(socket.room).emit('updateChat' , 'SERVER' , socket.username + 'has connect this room');
    //socket.emit('updateRooms',rooms, newRoom);
});

socket.on('privateMsg' , function (to ,Msg){
    sockets[users[to]].emit('updateChat' , {user : sockets[socket.id].username , mess : Msg});
});

socket.on('disconnect',function (){
    delete usernames[socket.username];
    //console.log(usernames);
    socket.broadcast.emit('updateChat', 'SERVER', socket.username + ' has disconnected');
    socket.emit('listUser' ,usernames, username);
    socket.broadcast.emit('listUser' , usernames ,username);
    if(socket.room)
        socket.leave(socket.room);
});
});

我不知道为什么网络中的某些代码可以使用这种方式,但我不能,我也更新了socket io。 请帮我修理一下。谢谢。

1 个答案:

答案 0 :(得分:0)

这一行:

sockets[users[to]].emit(...

需要改为:

sockets[users[to]].socket.emit(...

因为您要在sockets中存储条目,如:

sockets[socket.id] = {username : username  , socket : socket}