Socket.io - Socket splitting into rooms [on hold]


Socket.io - Socket splitting into rooms [on hold]



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?



Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.





Possible duplicate of Creating Rooms in Socket.io
– corn3lius
Mar 30 '17 at 17:04




1 Answer
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.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API