Reputation: 440
I have a nodejs backend and a react frontend. On nodejs I have socketio set up, on the client side I have the connection in the App component, and passed down using context. Now, using hooks, I can use the io variable globally and listen on client-side to events.
However, on server side, I have this IO variable also globally available, but how to use this on multiple pages? I have this code in server.ts:
const io = //initialize io
io.on('connection', (socket: any) => {
console.log('a user connected', socket.handshake.query);
socket.on('disconnect', () => {
console.log('user disconnected');
});
io.on('test', console.log);
});
But, in a different file, I have to initialize my connection using io.on()
again. How to work around this? I have a file called foo.controller.ts which has some actions around foo. In this file I want to listen all events related to foo.
Upvotes: 0
Views: 1233
Reputation: 1193
Create new file ex. socket.instance.js
, then create class to handle all socket's logic, like storing sockets list or something (it's up to you what you need);
Here is example of socket.instance.js
:
const Subject = require('rxjs').Subject;
class SocketInstance {
io = require('socket.io')();
sockets = new Set();
newSocket = new Subject();
constructor() {
this.io.listen(process.env.PORT);
this.io.on('connect', socket => {
this.sockets.add(socket);
this.handleNewSocket(socket);
socket.on('disconnect', () => {
this.sockets.delete(socket);
});
this.newSocket.next(socket);
});
}
handleNewSocket(socket) {
// logic here
}
}
const socketInstance = new SocketInstance();
module.exports = {socketInstance}
Then in any other file you can access to this instance like this:
// anotherServerFile.js
const socketInstance = require('./socket.instance').socketInstance;
socketInstance.io.emit('hello');
// yetAnotherFile.js
const socketInstance = require('./socket.instance').socketInstance;
socketInstance.newSocket.subscribe(socket => {
socket.on('test', console.log);
});
It's only basic example how to share your socket server instance between any other classes/files in your code. Everything depends on your needs
And on frontend situation is somewhat similar
Upvotes: 4