I'm trying to create a multiplayer game that creates new rooms for each two sockets that connect. How would I go about doing this? Can someone please provide an example?
Asked
Active
Viewed 288 times
0
-
Possible duplicate of [Creating Rooms in Socket.io](http://stackoverflow.com/questions/19150220/creating-rooms-in-socket-io) – corn3lius Mar 30 '17 at 17:04
1 Answers
1
As a starting point you can use the following example
const io = require('socket.io')()
/* room to join next connected socket */
let prevRoom = null
io.on('connection', socket => {
let room
if (prevRoom == null) {
/* create new room if there is no room with one player */
room = Math.random().toString(36).slice(2)
prevRoom = room
} else {
/* join existing room with one player and mark that it is now complete */
room = prevRoom
prevRoom = null
}
socket.join(room)
/* send message from one socket in this room to another */
socket.on('message', data => {
socket.broadcast.to(room).emit('message', data)
})
})
io.listen(3000)
The problem with this example is that in case one player from a room leaves the game, another will remain alone until he or she refreshes the page. Depending on the application you may need to add some logic here.

danroshko
- 466
- 2
- 8