I am currently working on developing a lobby system that allows players to invite each other using Socket io version 4. The process involves the client sending a request to create and join a room, followed by emitting messages to other clients in the same room. However, I have encountered an issue where the server successfully receives the message but fails to forward it to any clients within the room.
This is what my current code looks like:
Server
io.on('connection', (socket) => {
const token = extractToken(socket.handshake.headers)
const decodedToken = jwt.decode(token, { complete: true })
const user = decodedToken.payload.user_information
socket.leave(socket.id)
socket.id = user.id
socket.join(socket.id)
socket.on('room', (room) => {
socket.join(room)
})
socket.on('lobby', async (data) => {
const { message, room } = data
console.log(data)
socket.to(room).emit('lobby', message)
})
socket.on('disconnect', () => {
console.log(user.username + ' has disconnected')
})
})
Client
const connect = () => {
socket = io('localhost:8080', {
extraHeaders: {
authorization: 'bearer ' + token
}
})
socket.on('lobby', (msg) => {
console.log(msg)
const item = document.createElement('li')
item.textContent = msg
messagesList.appendChild(item)
})
}
messageForm.addEventListener('submit', async (e) => {
e.preventDefault()
if (messageInput.value) {
await socket.emit('room', roomInput.value)
socket.emit('lobby', { 'message': messageInput.value, 'room': roomInput.value })
messageInput.value = ''
}
})
While I can send global messages to all clients, I am unable to target a specific room. Despite clients joining the room upon request submission, they do not receive any messages from the room. Additionally, there are no logs indicating that clients disconnect during the process.
Various attempts to resolve this issue include utilizing the default namespace, ensuring both the server and socket emit the message, confirming the message object is defined, and verifying the room name is a string. Unfortunately, none of these solutions have proved successful thus far.
The server manages to receive the message but does not successfully broadcast it to the intended recipients within the specified room.