XMe*_*Men 44 javascript socket.io
我想在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;
Run Code Online (Sandbox Code Playgroud)
我想得到这个客户端的会话ID,我怎么能得到它?
Dan*_*lig 42
请仔细阅读我的入门知识.
更新:
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');
});
});
Run Code Online (Sandbox Code Playgroud)
blu*_*llu 38
在socket.io> = 1.0上,在触发connect事件后:
var socket = io('localhost');
var id = socket.io.engine.id
Run Code Online (Sandbox Code Playgroud)
小智 10
set,getAPI已被弃用*以下代码仅应用于版本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);
});
Run Code Online (Sandbox Code Playgroud)
现在可以通过socket.io连接对象的handshake属性访问分配给数据对象的所有属性.
io.sockets.on('connection', function (socket) {
console.log('sessionID ' + socket.handshake.sessionID);
});
Run Code Online (Sandbox Code Playgroud)
lus*_*chn 10
我只是遇到了同样的问题/问题并且像这样解决了它(只有客户端代码):
var io = io.connect('localhost');
io.on('connect', function () {
console.log(this.socket.sessionid);
});
Run Code Online (Sandbox Code Playgroud)
在服务器端
io.on('connection', socket => {
console.log(socket.id)
})
Run Code Online (Sandbox Code Playgroud)
在客户端
import io from 'socket.io-client';
socket = io.connect('http://localhost:5000');
socket.on('connect', () => {
console.log(socket.id, socket.io.engine.id, socket.json.id)
})
Run Code Online (Sandbox Code Playgroud)
如果socket.id, 不起作用,请确保在连接中on('connect')或连接后调用它。
| 归档时间: |
|
| 查看次数: |
99568 次 |
| 最近记录: |