[英]how to get session id of socket.io client in Client
我想在socket.io客户端中获取客户端的会话ID。
这是我的socket.io客户端:
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;
我想得到这个客户端的会话ID,我怎么能得到它?
请仔细阅读我的入门知识 。
更新:
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');
});
});
在socket.io> = 1.0上,在触发connect事件后:
var socket = io('localhost');
var id = socket.io.engine.id
set
和get
API * 以下代码仅应用于版本socket.io <0.9
请参阅 : http : //socket.io/docs/migrating-from-0-9/
它可以通过握手/授权机制完成。
var cookie = require('cookie');
io.set('authorization', function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
// if there is, parse the cookie
data.cookie = cookie.parse(data.headers.cookie);
// note that you will need to use the same key to grad the
// session id, as you specified in the Express setup.
data.sessionID = data.cookie['express.sid'];
} else {
// if there isn't, turn down the connection with a message
// and leave the function.
return accept('No cookie transmitted.', false);
}
// accept the incoming connection
accept(null, true);
});
现在可以通过socket.io连接对象的handshake属性访问分配给数据对象的所有属性。
io.sockets.on('connection', function (socket) {
console.log('sessionID ' + socket.handshake.sessionID);
});
我只是遇到了同样的问题/问题并且像这样解决了它(只有客户端代码):
var io = io.connect('localhost');
io.on('connect', function () {
console.log(this.socket.sessionid);
});
由于某些原因
socket.on('connect', function() {
console.log(socket.io.engine.id);
});
不适合我。 然而
socket.on('connect', function() {
console.log(io().id);
});
对我有用。 希望这对于那些在获取身份证方面也存在问题的人也很有帮助。 顺便说一句,我使用Socket IO> = 1.0。
尝试从你的代码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);});
试试这种方式。
var socket = io.connect('http://...');
console.log(socket.Socket.sessionid);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.