Home > Mobile >  Socket.IO join and leave only working part of the time
Socket.IO join and leave only working part of the time

Time:11-05

I am using socket.io for a project so clients can play a simple game. They are all added to a 'lobby' room upon connection. The lobby room is working fine 100% of the time. The part that is not working consistently is when a user creates a room. My script uses that user's UUID as the room name and the user joins the room. This is added to a list of active rooms that other players can then join. I am seeing two different issues with the join (neither throws an error of any kind).

The first is that the socket never joins the room and proceeds as if I had never called join at all. The second time the socket joins and is listed in the room, but disappears before the other player can join.

It should be noted that this same code was working consistently earlier today and I haven't changed anything that would affect it.

I tried adding a socket to a room via the socket.join() method, but the socket is only added part of the time and when it is added successfully it vanishes shortly afterward.

I am listening for the disconnect event and it is not fired at any time during this process as far as I can tell.

Here's some simplified code:

const http = require('http')
const server = http.createServer(app)
const { Server } = require('socket.io')
const io = new Server(server)

io.on('connection', async (socket) => {
  socket.join('lobby') // This works fine
  app.post('/api/game', async (req, res) => { // I have to put the endpoint inside of the connection handler because the class voted on it. I'm sure you don't like it either
    socket.join(req.id) // I am using the player's id as the room name
    // I do a few other things here
    res.send(roomId)
  }) // If I debug here the player is in the newly created room about 30% of the time

app.put('/api/game/join', async (req, res) => {
    //socket.leave('lobby') // leaving the lobby doesn't do anything either. The player is still in the lobby after this
    await joinRoom(req.body.room.id) // using await did not make a difference in behavior
    res.send(roomId)
  })

As noted in the code, the same issues seem to be affecting socket.leave('room') as well. Does this have something to do with my callbacks?

This is happening on an express server.

Thank you for any help, it is greatly appreciated!

CodePudding user response:

I found the answer if anyone ever runs into a similar problem. Turns out putting a socket.join() inside an express endpoint causes some major wacky behavior. Maybe some kind of race condition? Regardless I was able to join the room using a normal socket event and handle the endpoint separately.

  • Related