Get SocketIO ID from Express Request

隐身守侯 提交于 2021-01-08 15:41:25

问题


A user of my system will access a page to pull lots of data, at least 500 records, from server Foo. Once 50 records have been gathered, Express will begin to render the page to display the first 50 records to the user (only the first 50 records need to be displayed initially). Once the system has pulled all 500 records from Foo I want to send the user a message letting them know that the operation is complete.

My idea is to call the socket emit function once the processing is complete, however I am unsure how to retrieve the socket ID from the request object provided when the user GETs the page. Is it possible or do I need to create a map of request ID's to Socket ID's?


回答1:


There seems to be quite a few viable approaches. Here is a simple one:

Create a unique index for each GET request, store it in the server and render it into the client page/code.

On the client side, call this:

socket.on('data_fetched', () => alert('data fully fetched'));
socket.emit('request_data', UNIQUE_INDEX);

On the server side, have something like this:

const sockets = {};
...
socket.on('request_data', uniq_idx => {
  sockets[uniq_idx] = socket;
});

Then once the data is fully fetched, you can call:

sockets[uniq_idx].emit('data_fetched');
sockets[uniq_idx].disconnect(true);
delete sockets[uniq_idx];

Using express-socket.io-session

const sharedsession = require('express-socket.io-session');
const io = require('socket.io').listen(server);
io.use(sharedsession(session));

With that, you can access your session id through socket.handshake.session.id, so the code becomes:

// Client socket
socket.on('data_fetched', () => alert('data fully fetched'));
socket.emit('request_data');

// Server socket
const sockets = {};
...
socket.on('request_data', () => {
  sockets[socket.handshake.session.id] = socket;
});

// Call once finished fetching data
sockets[req.session.id].emit('data_fetched');
sockets[req.session.id].disconnect(true);
delete sockets[req.session.id];

You can make it even shorter by using the default connection event instead of creating a custom one (request_data). Automatically disconnecting when done is also optional.

If you want to update your session in web socket, you can do as follow:

socket.handshake.session.username = 'dave';
socket.handshake.session.save();

Or simply initialize express-socket.io-session as

sharedsession(session, {
  autoSave:true
});


来源:https://stackoverflow.com/questions/44137917/get-socketio-id-from-express-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!