63 lines
1.7 KiB
JavaScript
63 lines
1.7 KiB
JavaScript
// Include dependencies
|
|
var app = require('express')();
|
|
var http = require('http').createServer(app);
|
|
var io = require('socket.io')(http)
|
|
|
|
// Set variables
|
|
const port = 9966;
|
|
var users = 0;
|
|
|
|
// Function for easy server broadcasts
|
|
function serverMsg(content) {
|
|
return {
|
|
'username': 'Server',
|
|
'mailHash': '470965550d3f019830c421f0535d9268',
|
|
'message': content
|
|
}
|
|
}
|
|
|
|
// Serve Client
|
|
app.get('/', function(req, res){
|
|
res.sendFile(__dirname + '/index.html');
|
|
});
|
|
|
|
// Socket.io server side
|
|
io.on('connection', function (socket) {
|
|
// Send identification request to client
|
|
socket.emit('user_identify');
|
|
|
|
// Bind username and mailhash to client
|
|
socket.on('user_login', function (user) {
|
|
socket.username = user.username;
|
|
socket.mailHash = user.mailHash;
|
|
io.emit('message_receive', serverMsg(`${socket.username} has connected`));
|
|
users++;
|
|
});
|
|
|
|
// Send disconnect broadcast to all clients
|
|
socket.on('disconnect', function () {
|
|
io.emit('message_receive', serverMsg(`${socket.username} has disconnected`));
|
|
users--;
|
|
});
|
|
|
|
// Handle messages
|
|
socket.on('message_send', function (message) {
|
|
// Build message data for clients
|
|
if (message !== '') {
|
|
var msg = {
|
|
'username': socket.username,
|
|
'mailHash': socket.mailHash,
|
|
'message': message
|
|
}
|
|
// Send message to clients
|
|
io.emit('message_receive', msg);
|
|
} else {
|
|
socket.emit('message_receive', serverMsg(`Empty messages will not be sent.`));
|
|
}
|
|
});
|
|
});
|
|
|
|
// Start http server
|
|
http.listen(port, function() {
|
|
console.log(`Listening on port ${port}`);
|
|
}); |