how to get session id of socket.io client in Clien

2019-01-16 10:16发布

I want to get session id of client in my socket.io client.

here is my socket.io client :

var socket = new io.Socket(config.host, {port: config.port, rememberTransport: false});
    // when connected, clear out display
    socket.on('connect',function() {
        console.log('dummy user connected');
    });
    socket.on('disconnect',function() {
        console.log('disconnected');
    });
    socket.connect();
    return socket;

I want to get session id of this client , how can i get that ?

7条回答
你好瞎i
2楼-- · 2019-01-16 10:28

On socket.io >=1.0, after the connect event has triggered:

var socket = io('localhost');
var id = socket.io.engine.id
查看更多
干净又极端
3楼-- · 2019-01-16 10:29

Try from your code socket.socket.sessionid ie.

    var socket = io.connect('http://localhost');
alert(socket.socket.sessionid);
  var sendBtn= document.getElementById('btnSend');
  sendBtn.onclick= function(){
var userId=document.getElementById('txt1').value;
var userMsg = document.getElementById('txt2').value;
socket.emit('sendto',{username: userId, message: userMsg});
};

  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
  socket.on('message',function(data){ console.log(data);});
查看更多
做自己的国王
4楼-- · 2019-01-16 10:30

For some reason

socket.on('connect', function() {
    console.log(socket.io.engine.id);
}); 

did not work for me. However

socket.on('connect', function() {
    console.log(io().id);
}); 

did work for me. Hopefully this is helpful for people who also had issues with getting the id. I use Socket IO >= 1.0, by the way.

查看更多
▲ chillily
5楼-- · 2019-01-16 10:31

I just had the same problem/question and solved it like this (only client code):

var io = io.connect('localhost');

io.on('connect', function () {
    console.log(this.socket.sessionid);
});
查看更多
Summer. ? 凉城
6楼-- · 2019-01-16 10:39

Have a look at my primer on exactly this topic.

UPDATE:

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

app.listen(8080);
sio = sio.listen(app);

sio.on('connection', function (client) {
  console.log('client connected');

  // send the clients id to the client itself.
  client.send(client.id);

  client.on('disconnect', function () {
    console.log('client disconnected');
  });
});
查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-01-16 10:49

Try this way.

                var socket = io.connect('http://...');
                console.log(socket.Socket.sessionid);
查看更多
登录 后发表回答