when you connect socket from the client you have to pass the user id along with socket and you have to catch it and use it to identify the socket for that user.
const socket = io();
io('/', { query: "id=user id here" });
Server side code here:
var connectedUsers = {};
var io = socket.listen(server);
io.on('connection', function(socket){
var userId = socket.handshake.query['id'];
var connectedUser = {id:userId, socket:socket}
// every socket connection will have unique socket.id which we use to store in socket and identify if disconnected.
connectedUsers[socket.id] = connectedUse
socket.on('disconnect', function() {
for(var i in connectedUsers)
if(connectedUsers[i].socket.id === socket.id){
delete connectedUsers[i];
}
});
});
Now in your post request you have to identify the user by the same id and get the respective socket for the user.
app.post('/request', function(req, res) {
var userId = 'write your code to get user id';
if(connectedUsers[userId])
connectedUsers[userId].socket.emit('message', {});
else
console.log('User not online');
res.end();
});
Note: this is just a sample will not work until you handle fetching user id properly.
If you can identify user only after login, you have to create a socket event for user login and emit user id to server from client and write 'connection' code inside the login event.