arnweb-chat/index.js

59 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-08-21 20:32:42 +02:00
// 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;
2019-08-21 21:29:48 +02:00
// Function for easy server broadcasts
function serverMsg(content) {
return {
'username': 'Server',
'mailHash': '470965550d3f019830c421f0535d9268',
'message': content
}
}
2019-08-21 20:32:42 +02:00
// Serve Client
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
// Socket.io server side
io.on('connection', function (socket) {
2019-08-21 21:29:48 +02:00
// Send identification request to client
2019-08-21 20:32:42 +02:00
socket.emit('user_identify');
2019-08-21 21:29:48 +02:00
// 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++;
2019-08-21 20:32:42 +02:00
});
2019-08-21 21:29:48 +02:00
// Send disconnect broadcast to all clients
2019-08-21 20:32:42 +02:00
socket.on('disconnect', function () {
2019-08-21 21:29:48 +02:00
io.emit('message_receive', serverMsg(`${socket.username} has disconnected`));
2019-08-21 20:32:42 +02:00
users--;
});
// Handle messages
2019-08-21 21:29:48 +02:00
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
2019-08-21 20:32:42 +02:00
io.emit('message_receive', msg);
});
});
2019-08-21 21:29:48 +02:00
// Start http server
2019-08-21 20:32:42 +02:00
http.listen(port, function() {
console.log(`Listening on port ${port}`);
});