Skip to content

Instantly share code, notes, and snippets.

@porsager
Forked from cmnstmntmn/server.js
Created November 9, 2016 10:32
Show Gist options
  • Save porsager/ad0af8934d7c3fc18434f286ca2294de to your computer and use it in GitHub Desktop.
Save porsager/ad0af8934d7c3fc18434f286ca2294de to your computer and use it in GitHub Desktop.
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