0

can we pass a parameter to io.on(); which could be used as socket.id during connection instead of the automatic generated socket id? if so...can it be done via var socket=io(); ?

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

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

    console.log("connected");

    socket.on('disconnect',function(data){

        console.log( socket.id+" disconnected");    
    });
});

http.listen(3000,function(){

    console.log("listening on port 3000");  
});

what i have been doing till now is to store socket id in session and then overwrite the auto generated socket id with it...its not a good approach though. i dont want to change the socket id to a custom id after the connection has occurred, i want the connection to initialise the socket with that custom id in the first place.

`

<html>
    <head>
    <script src="/socket.io/socket.io.js"></script>
    <script>

        var socket=io();
    </script>
    ...</html>
rsSpeaks
  • 3
  • 4
  • 1
    Does it suppose to be `var server = require('http').createServer(app)`? – FisNaN Mar 21 '18 at 09:38
  • nope.. http.listen(); am new to this so might to be what u asked.. the var socket=io(); is inside my index.html script..if that helps...or should i put the whole code down here? – rsSpeaks Mar 21 '18 at 11:05
  • Always includes all the essential parts of your code while keep it short and executable. So people can test it and troubleshoot your problem easier. – FisNaN Mar 21 '18 at 11:14
  • could u take a look again – rsSpeaks Mar 21 '18 at 11:38
  • Possible duplicate of [Socket.io custom client ID](https://stackoverflow.com/questions/7702461/socket-io-custom-client-id) – James Mar 21 '18 at 11:41
  • https://stackoverflow.com/questions/6805432/how-to-uniquely-identify-a-socket-with-node-js – FisNaN Mar 21 '18 at 11:48
  • nope.. ill try to explain bit more... when user connects..a socketId is generated...user disconnects..socketId gets terminated..if user disconnects and then connects again(refresh)..a new socketId is generated for the same user...but i have the original socketId stored in session...is it possible to use that while the connection is established...and am not asking about changing socket id after connection is established..the reconnection should be initiated with the origianl id from session..thnx...i know its a bit much – rsSpeaks Mar 21 '18 at 12:04

1 Answers1

0

What I did was set the socket.id equal to what I wanted it to be. When you do the socket.join, with that it'll keep the correct socket id you set earlier. Not sure if that's what you're referring to.

user2644360
  • 71
  • 1
  • 2
  • 9