Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io Identify User for Socket

I write some code example that identifi connected users via socket.io... So now I must write a code on index page to comunicate with users.

The code is below and HOW to send a message to user[1] "Welcome" and for user[2] "HI men" and also limit connection fr 2 users. so when 2 user connected then anybody else cant connect..

Index.html:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect();
  var users;
  socket.on('hello', function (data) {
    console.log(data.hello);
  });
  socket.on('listing', function (data) {
     users = data; 
  });
  socket.on('chat', function (message) {
     console.log(message); 
  });
  socket.on('message', function (message) {
     console.log(message); 
  });
  function chat (message) {
    socket.emit('chat', message);   
  }
  function message (user, message) {
    socket.emit('message', {
       user: user,
       message: message
    });
  }
</script>

app.js

var express = require('express');
var app = express.createServer();
var io = require('socket.io').listen(app);

app.listen(3000);

app.use(express.static(__dirname));

var users = {};
var userNumber = 1;

function getUsers () {
   var userNames = [];
   for(var name in users) {
     if(users[name]) {
       userNames.push(name);  
     }
   }
   return userNames;
}

io.sockets.on('connection', function (socket) {
  var myNumber = userNumber++;
  var myName = 'user#' + myNumber;
  users[myName] = socket;

  socket.emit('hello', { hello: myName });
  io.sockets.emit('listing', getUsers());

  socket.on('chat', function (message) {
    io.sockets.emit('chat', myName + ': ' + message);
  });
  socket.on('message', function (data) {
     users[data.user].emit('message', myName + '-> ' + data.message); 
  });

  socket.on('disconnect', function () {
    users[myName] = null;
    io.sockets.emit('listing', getUsers());
  });
});

app.listen(process.env.PORT);
like image 442
beginerplus Avatar asked May 20 '12 12:05

beginerplus


2 Answers

I know it has been a long time since you asked this, but just 4 days ago I published a module for node js, express and socket.io which manages that exactly thing you wanted. Check the Usage and Example; I hope you will find this module helpful!

You can install it via NPM socket.io.users This is a node js module for socket.io applications. One user per client.

Some of the usage code:

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 ITS OWN users object list,
but the Id of a user of any other namespace may 
have 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 the 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.store.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.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 :(');
});

//...server.listen blabla..
like image 172
kataras Avatar answered Sep 19 '22 09:09

kataras


You can start by taking a look at how to configure authorization with Socket.io. The handshakeData provided by the callback can be modified there (ie: add a username property), and any changes will be accessible via socket.handshake in your app.js (via the object passed in to the callback for io.sockets.on('connection',..). Using request header information that's also accessible from the handshakeData, you can set user values within the authorization callback (ie: from a database) so you can identify the user for the given socket in your app.js.

Here's a similar example

like image 28
Wes Johnson Avatar answered Sep 21 '22 09:09

Wes Johnson