Socket.io Emit To Specific Client In Tabs
I am using socket.io with angular. It works fine but my problem is that it emits to all the tabs opened in Chrome. The current workflow is the app will be opened in multiple tabs t
Solution 1:
Ok, I was able to solve this problem after some trial and error. Looking through SO, there were solutions based on express sessions shared between express and socket. While it worked, i was not able to isolate individual tabs. My use case is to set this as an app that can be used in multiple instances across browsers (think of it as quotation engine). The below solution worked for me.
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 = newDate();
}
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
returnthis.$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 HEADERvar 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.
Post a Comment for "Socket.io Emit To Specific Client In Tabs"