diff --git a/index.html b/index.html index 41db75d..7270b28 100644 --- a/index.html +++ b/index.html @@ -21,17 +21,16 @@ // Wait for server response and identify client socket.on('user_identify', function(){ - socket.emit('user_login', 'Bart'); + socket.emit('user_login', { + 'username': 'Bart', + 'mailHash': '289e66591abdb9c2d4cb15517f0fd8d8' + }); }); // Send data to server on form submit $('form').submit(function(e){ e.preventDefault(); - var msg = { - 'username': $('#username').val(), - 'message': $('#message').val() - } - socket.emit('message_send', msg); + socket.emit('message_send', $('#message').val()); $('#message').val(''); return false; }); diff --git a/index.js b/index.js index b39dc20..f984796 100644 --- a/index.js +++ b/index.js @@ -7,6 +7,15 @@ var io = require('socket.io')(http) 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'); @@ -14,29 +23,37 @@ app.get('/', function(req, res){ // Socket.io server side io.on('connection', function (socket) { - // Log connects / disconnects - console.log('User connected'); + // Send identification request to client socket.emit('user_identify'); - socket.on('user_login', function (username) { - io.emit('message_receive', { 'username': 'Server', 'message': `${username} has connected`}); + // 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++; }); - users++; + // Send disconnect broadcast to all clients socket.on('disconnect', function () { - console.log('User disconnected'); + io.emit('message_receive', serverMsg(`${socket.username} has disconnected`)); users--; }); - console.log(`Users online: ${users}`); // Handle messages - socket.on('message_send', function (msg) { - console.log(msg.username + ': ' + msg.message); + socket.on('message_send', function (message) { + // Build message data for clients + var msg = { + 'username': socket.username, + 'mailHash': socket.mailHash, + 'message': message + } + // Send message to clients io.emit('message_receive', msg); }); }); -// Log on server +// Start http server http.listen(port, function() { console.log(`Listening on port ${port}`); }); \ No newline at end of file