socket.io.users来自示例的错误

时间:2016-05-19 15:45:39

标签: node.js sockets socket.io

所以我100%复制粘贴下面链接的代码,我得到以下错误。我已经安装了所有必需的依赖项。我之前使用过socket.io没有问题,但从来没有使用socket.io.users。目标是将每台PC识别为用户。

var chatUsers = socketUsers.Users.of('/chat'); //
                                  ^
TypeError: Object #<Users> has no method 'of'
    at Object.<anonymous> (/var/www/100moneta/components_not_larval/socket-user.js:16:35)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

我的代码:

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var socketUsers = require('socket.io.users');

socketUsers.Session(app);//IMPORTANT 

var rootIo = require('socket.io')(server); //default '/' as namespace. 
var chatIo = rootIo.of('/chat');


var rootUsers = socketUsers.Users; /* default '/' as namespace. Each namespace has IT's OWN users object list,
but the Id of a user of any other namespace may has the same value if request comes from the same client-machine-user.
This makes easy to keep a kind of synchronization between all users of all different namespaces. */

var chatUsers = socketUsers.Users.of('/chat'); // 


rootIo.use(socketUsers.Middleware());//IMPORTANT but no errors if you want to skip it for a io.of(namespace) that you don't want the socket.io.users' support. 

chatUsers.use(socketUsers.Middleware());

chatUsers.on('connected',function(user){
    console.log(user.id + ' has connected to the CHAT');
    user.set('username', 'username setted by server side'); /*at the store property you can store any type of properties
    and objects you want to share between your user's sockets. */
    user.socket.on('any event', function(data){ //user.socket is the current socket, to get all connected sockets from this user, use: user.sockets 

    });
    chatIo.emit('set username',user.get('username')); //or user.store.username 
});

rootUsers.on('connected',function(user){
    console.log('User has connected with ID: '+ user.id);
});



rootUsers.on('connection',function(user){
    console.log('Socket ID: '+user.socket.id+' is user with ID: '+user.id);
});

rootUsers.on('disconnected',function(user){
    console.log('User with ID: '+user.id+'is gone away :(');
});



//You can still use the io.on events, but the execution is after connected and connection of the 'users' and 'chatUsers', no matter the order. 
rootIo.on('connection',function(socket){
    console.log('IO DEBUG: Socket '+ socket.id+ ' is ready \n');
});

链接代码和教程:https://www.npmjs.com/package/socket.io.users

0 个答案:

没有答案