42 lines
1.0 KiB
JavaScript
42 lines
1.0 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;
|
|
|
|
// Serve Client
|
|
app.get('/', function(req, res){
|
|
res.sendFile(__dirname + '/index.html');
|
|
});
|
|
|
|
// Socket.io server side
|
|
io.on('connection', function (socket) {
|
|
// Log connects / disconnects
|
|
console.log('User connected');
|
|
socket.emit('user_identify');
|
|
|
|
socket.on('user_login', function (username) {
|
|
io.emit('message_receive', { 'username': 'Server', 'message': `${username} has connected`});
|
|
});
|
|
|
|
users++;
|
|
socket.on('disconnect', function () {
|
|
console.log('User disconnected');
|
|
users--;
|
|
});
|
|
console.log(`Users online: ${users}`);
|
|
|
|
// Handle messages
|
|
socket.on('message_send', function (msg) {
|
|
console.log(msg.username + ': ' + msg.message);
|
|
io.emit('message_receive', msg);
|
|
});
|
|
});
|
|
|
|
// Log on server
|
|
http.listen(port, function() {
|
|
console.log(`Listening on port ${port}`);
|
|
}); |