Reputation: 6267
I have implemented socket.io in an express server. Everything works, but I would like to avoid having a long socket script in my main file. I have thus created a separate service to handle socket logic in another file:
main.js:
io.on("connect", SocketManager(io))
socketManager.js:
const SocketManager = (io) => {io.on("connect", ()=> do stuff}
But when doing so, I can only use io instance. Socket is undefined, which is quite unfortunate given I must access it to achieve specific tasks. Sadly, I can't just pass socket as a second argument to SocketManager. How to fix this?
Upvotes: 0
Views: 116
Reputation: 708136
Your code is ignoring the socket
that is passed into the connect
event so you're missing your opportunity to use the actual newly created socket.
To fix, change this:
io.on("connect", SocketManager(io))
to this:
SocketManager(io)
All you want to do there is initialize your socket manager and pass it the io
instance and let it listen for the connect
event itself.
Then, in your SocketManager
code, you want to pay attention to the socket
argument that is passed into the connect
event. So, change this:
const SocketManager = (io) => {io.on("connect", ()=> do stuff}
to this:
const SocketManager = (io) => {
io.on("connect", (socket) => {
// do stuff using newly connected socket in here
});
});
Upvotes: 1