Created
November 9, 2016 10:13
-
-
Save cmnstmntmn/4e18d62de2cdcdab468f497e37488f98 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const Primus = require('primus'), | |
path = require('path'), | |
chalk = require('chalk'), | |
log = console.log, | |
primusRequests = require('primus-requests') | |
const sockets = module.exports | |
sockets.listen = function(server) { | |
const primus = sockets.primus = new Primus(server, { | |
transformer: 'uws', | |
plugin: { | |
requests: primusRequests | |
} | |
}) | |
primus.save('workspace/source/js/utils/primus.js') | |
var connections = [] | |
var id; | |
var reason = ''; | |
var connectionIndex = (id) => connections.findIndex(el => el.ws === id); | |
var getClients = (role = null) => { | |
return role ? connections.filter(el => el.role === role) : connections | |
} | |
var broadcast = (socket, event, clients, message = 'hello to all from the server') => { | |
clients.lenght > 0 ? clients.map((client, i) => socket.write('message for clients', message)) : null | |
} | |
primus.on('connection', socket => { | |
id = socket.id; | |
// asteptam mesaj custom de la client | |
socket.on('open', (data, response) => { | |
connections.push({ ws: socket.id }) | |
// Adaugam la obiectul din conexiune | |
if (!!connections.find(el => el.uid === data.uid && el.role === 'player')) { | |
reason = !!connections.find(el => el.uid === data.uid && el.role === 'player') ? data.name + ' is already connected' : 'rejected' | |
spark.end(undefined, { reconnect: true }) | |
callback('Closed! Reason: ', reason) | |
} else if (connections[connectionIndex(id)]) { | |
delete data.api | |
Object.assign(connections[connectionIndex(id)], data) | |
if (!!data.uid) | |
log('%s - %s joined the game as a %s, having id %s', chalk.gray(connections[connectionIndex(id)].ws), chalk.green(connections[connectionIndex(id)].name), chalk.green(connections[connectionIndex(id)].role), chalk.green(connections[connectionIndex(id)].uid)); | |
else | |
log('%s - New %s joined the party!', chalk.yellow(connections[connectionIndex(id)].ws), chalk.yellow(connections[connectionIndex(id)].role)); | |
} | |
log('conexiuni', connections.length) | |
broadcast(socket, 'join', getClients('presenter')) | |
// Send to client | |
response(connections[connectionIndex(id)]) | |
}) | |
}) | |
primus.on('disconnection', function(socket) { | |
log('%s connection has been closed. Reason: %s', chalk.red(id), chalk.red(reason)); | |
connections.length > 0 ? connections.splice(connectionIndex(id), 1) : null | |
}); | |
connections.length === 0 ? log(chalk.gray('Niciun client conectat')) : null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment