Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io custom client ID

I'm making a chat app with socket.io, and I'd like to use my custom client id, instead of the default ones (8411473621394412707, 1120516437992682114). Is there any ways of sending the custom identifier when connecting or just using something to track a custom name for each ID? Thanks!

like image 854
pmerino Avatar asked Oct 09 '11 09:10

pmerino


People also ask

What is the difference between Socket.IO and socket IO client?

socket-io. client is the code for the client-side implementation of socket.io. That code may be used either by a browser client or by a server process that is initiating a socket.io connection to some other server (thus playing the client-side role in a socket.io connection).

Does Socket.IO use WSS?

Note: You can use either https or wss (respectively, http or ws ).


1 Answers

You can create an array on the server, and store custom objects on it. For example, you could store the id created by Socket.io and a custom ID sent by each client to the server:

var util = require("util"),     io = require('/socket.io').listen(8080),     fs = require('fs'),     os = require('os'),     url = require('url');      var clients =[];      io.sockets.on('connection', function (socket) {          socket.on('storeClientInfo', function (data) {              var clientInfo = new Object();             clientInfo.customId         = data.customId;             clientInfo.clientId     = socket.id;             clients.push(clientInfo);         });          socket.on('disconnect', function (data) {              for( var i=0, len=clients.length; i<len; ++i ){                 var c = clients[i];                  if(c.clientId == socket.id){                     clients.splice(i,1);                     break;                 }             }          });     }); 

in this example, you need to call storeClientInfo from each client.

<script>     var socket = io.connect('http://localhost', {port: 8080});      socket.on('connect', function (data) {         socket.emit('storeClientInfo', { customId:"000CustomIdHere0000" });     }); </script> 

Hope this helps.

like image 193
oscarm Avatar answered Oct 04 '22 11:10

oscarm