Below implementation solves the problem of communicating the socket that initiated the API request. It follows the idea of sending the socketid through the request. Sharing session variables did not work when the user opens multiple tabs in the same browser as the browser assigns same cookie/session across tabs.
Server code
socketio.on('connection', function(socket) {
socket.address = `${socket.request.connection.remoteAddress}:${socket.request.connection.remotePort}`;
// USED TO SET THE SOCKET ID FOR THE REQUEST
socket.emit('initialize', socket.id)
socket.connectedAt = new Date();
}
Client Code
In Angular, i setup an initialize event to store the specific socket Id for the tab
this.socket.on('initialize', socketid => {
console.log(socketid)
this.socketid = socketid
})
When the request is sent to express, i send the socketid as a header
return this.$http({
method: 'POST',
withCredentials: true,
host: '127.0.0.1',
data: sim_data,
port: 3000,
responseType: "arraybuffer",
headers: {
"X-socketid": this.socketid
},
url: '/api/blah'
})
Server Code
Finally, when express processes the POST or get i emit to the socketid from Header
// GET SOCKET ID FROM HEADER
var socket_id = req.headers['x-socketid']
if (typeof socket_id !== 'undefined' && socket_id) {
var io = req.app.get('io')
io.sockets.connected[socket_id].emit('pyr', output)
}
My next step is to integrate this with user authorization.