Created
November 4, 2018 12:13
-
-
Save junajan/f481aa13551cadc779fb5dde27e0a30d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// == Client 1 == | |
var socket = require('socket.io-client')('http://localhost'); | |
const gameInfo = null | |
socket.emit('createGame', (createdGame) => { | |
gameInfo = createdGame | |
}) | |
socket.on('clientConnected', (clientId) => { | |
}) | |
// == Client 1 == | |
var socket = require('socket.io-client')('http://localhost'); | |
const gameInfo = null | |
socket.emit('gameCreated', (game) => { | |
// connect first created game | |
socket.emit('joinGame', (game.id) => { | |
gameInfo = game | |
}) | |
}) | |
// == Server side == | |
// server - some server instance | |
const _ = require('lodash'); | |
const SocketIo = require('socket.io'); | |
const io = SocketIo(server); | |
const uuidv1 = require('uuid/v1'); | |
const games = {} | |
io.on('connection', (client) => { | |
console.log('SocketIO::connect', client.id); | |
client.on('createGame', (cb) => { | |
// check if client.id is not in any game right now | |
const isClientInGame = _(games) | |
.map('clients') | |
.flatten() | |
.find(id => id === client.id) | |
if(isClientInGame) | |
return cb({ | |
error: 'Already in game, cant create a new one' | |
}) | |
const id = uuidv1() | |
games[id] = { | |
id, | |
roomName: `game-${id}`, | |
clients: [client.id] | |
} | |
client.join(roomName) | |
cb(games[uuidv1()]) | |
io.emit('gameCreated', games[id]) | |
}) | |
client.on('joinGame', (id, cb) => { | |
// check if game exists | |
if(!games[id]) | |
return cb({ | |
error: 'Game not found' | |
}) | |
// check if client.id is not in any game right now | |
const isClientInGame = _(games) | |
.map('clients') | |
.flatten() | |
.find(id => id === client.id) | |
if(isClientInGame) | |
return cb({ | |
error: 'Already in game, cant create a new one' | |
}) | |
// return game and join the room | |
games[id].clients.push(client.id) | |
client.join(games[id].roomName) | |
io.to(games[id].roomName).emit('clientConnected', client.id) | |
cb(games[id]) | |
}) | |
client.on('disconnect', () => { | |
console.log('SocketIO::disconnect', client.id); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment