Skip to content

Instantly share code, notes, and snippets.

@junajan junajan/sockets.js
Created Nov 4, 2018

Embed
What would you like to do?
// == 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
You can’t perform that action at this time.