This repository was archived by the owner on May 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchatServer.js
More file actions
82 lines (68 loc) · 2.11 KB
/
Copy pathchatServer.js
File metadata and controls
82 lines (68 loc) · 2.11 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const net = require('net');
const EventEmitter = require('events');
const logger = require('./logger');
const logging = require('./dataLogging');
const ClientConnection = require('./clientConnection');
const Config = require('./config');
if(Config.livePort == null && Config.port == null) {
console.log('config needs port');
process.exit(1);
return;
}
var start = function() {
if(module.listening) return;
module.chatServer = net.createServer(function(socket) {
socket.clientConnection = ClientConnection.createNew(socket);
socket.on('data', (raw) => {
var rawStr = raw.toString().trim();
var lines = rawStr.split('\n');
for(var i in lines) {
var line = lines[i];
if(line.trim() == "")
continue;
try {
var obj = JSON.parse(line);
if(obj.type == null) {
logger.error("Received invalid call from client", line);
} else if(socket.clientConnection instanceof EventEmitter) {
if(!socket.clientConnection.emit(obj.type, obj)) {
logger.log('Attempted to emit ' + obj.type + ' but no handler was found');
}
}
} catch(e) {
console.error(e);
logger.error("Error receiving call from client", line);
}
}
});
socket.on('error', (error) => {
});
socket.on('close', () => {
if(socket.clientConnection != null) {
socket.clientConnection.onDisconnect();
}
});
socket.on('end', () => {
if(socket.clientConnection != null) {
socket.clientConnection.onDisconnect();
}
});
});
if(Config.livePort == null) {
var port = Config.port;
} else {
var port = Config.livePort;
}
module.chatServer.listen(port);
module.listening = true;
logger.log("Listening on port " + (port));
}
var shutdown = function() {
if(module.chatServer != null && module.chatServer.listening) {
module.chatServer.close(function(err) {
logging.logGlobalRoomEvent('sys', 'No longer accepting connections.');
logger.log("No longer listening...");
})
}
}
module.exports = {start, shutdown};