I am using 4.2.0 version of socket.io on client and server side. Server is on localhost 3000 and client on localhost 5000.
In first version of backend code everything works fine, I am getting a message on server and on the client immediately, this is a code which working fine:
app is a constructor of Express Application.
import * as socketio from 'socket.io';
const io: socketio.Server = new socketio.Server({
cors: {
origin: "http://localhost:5000"
}
});
const server: http.Server = app.listen(); // it knows that it should works on 3000
io.attach(server);
io.of('/play/multi-player-lobby').on('connection', (socket: socketio.Socket) => {
socket.emit('messageFromServer', { data: "req.session.user!.login" });
socket.on('dataToServer', (dataFromClient: object) => {
console.log(dataFromClient)
});
});
But this version of code has a downside, I cannot pass to client side user data which is logged in, thats why I want to use io in a get Route like in second version of my code:
Server file
const server: http.Server = app.listen();
io.attach(server);
app.app.set('socketio', io);
And route file:
getMethod(req: Request, res: Response) {
var io = req.app.get('socketio');
io.of('/play/multi-player-lobby').on('connection', (socket: socketio.Socket) => {
socket.emit('messageFromServer', { data: req.session.user!.login });
socket.on('dataToServer', (dataFromClient: object) => {
console.log(dataFromClient)
});
});
res.json({ isLoggedIn: req.session.isLoggedIn, user: req.session.user })
}
This version of code is also working, but I get the data after 30 seconds! Why? How to fix that?
Thanks for a help. Best regards from Misugi ;)