-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
61 lines (48 loc) · 2.01 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const net = require('net');
const os = require('os');
const global = require('./global');
const commandHandler = require('./commandHandler');
const user = require('./user');
const messaging = require('./messaging');
let args = process.argv.slice(2);
let port = args.length > 0 ? args[0] : 1337;
let localIP = [].concat(...Object.values(os.networkInterfaces())).find(x => !x.internal && x.family === 'IPv4')?.address
function createServer() {
var server = net.createServer(function (socket) {
socket.setEncoding('utf8');
// color code red \x1b\[31m
messaging.sendRawLine(socket, "Globaler Group Chat\r\n!!! Achtung nicht verschlüsselt !!!\r\n\r\nBenutzernamen eingeben: ");
socket.on('data', function (message) {
message = message.replace(/\r|\n/g, '');
if (message == '') return;
if (!global.connectionExits(socket)) {
// First message, user set username
user.setNewUser(socket, message);
} else if (message.at(0) == "/") {
// Message is a command
commandHandler.query(socket, message);
} else {
// Send a Text message
messaging.broadcast(socket, message);
}
})
socket.on('close', function () { disconnectHandler(socket) });
socket.on('timeout', function () { disconnectHandler(socket) });
socket.on('error', function () { disconnectHandler(socket) });
});
server.listen(port, '0.0.0.0', () => {
console.log("Server started\nTo connect a client: 'nc " + localIP + " " + server.address().port + "'");
});
}
function disconnectHandler(socket) {
let item = global.getConnection(socket);
let additionalMsg = (item.goodbye && item.goodbye != '') ? ' und sagt: ' + item.goodbye : ''
global.allConnections.splice(global.allConnections.indexOf(item), 1);
user.updateLongestUsername();
messaging.broadcastRaw(undefined, item.username + " disconnected" + additionalMsg);
}
function closeSocketConnection(socket) {
socket.destroy();
}
createServer();
module.exports.closeSocketConnection = closeSocketConnection;