-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket_server.js
59 lines (53 loc) · 1.76 KB
/
websocket_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
const net = require('net');
const Events = require('events');
const os = require('os');
const ifaces = os.networkInterfaces();
const connectionHandler = require('./connection_handler');
module.exports = class {
host = 'localhost';
port = '8080';
noServer = false;
eventHandler;
server;
// params option is for server option. Like port and host
// params handler is for handler event and function. Like on data, on end
constructor(options, handler) {
if(typeof options !== 'object') {
handler = options;
options = {};
} else if(options.hasOwnProperty('noServer') && options.noServer) {
this.noServer = true;
}
this.parseOptions(options);
this.parseHandler(handler);
this.createServer();
}
parseHandler(handler) {
this.eventHandler = new Events();
const socket = {
on: (event, handler) => {
this.eventHandler.on(event, handler)
}
}
handler(socket);
}
createServer() {
if(this.noServer) {
return;
}
this.server = net.createServer();
this.server.on('connection', (socket) => {
new connectionHandler(socket, this.eventHandler, {socketType: 'NET'});
})
this.server.listen(this.port, this.host, () => {
console.log(`Server started at ws://${this.host}:${this.port}`);
});
}
handleHttpServerConnection(request) {
new connectionHandler(request, this.eventHandler, {socketType: 'HTTP'});
}
parseOptions(options) {
this.host = options.hasOwnProperty('host') ? options.host : this.host;
this.port = options.hasOwnProperty('port') ? options.port : this.port;
}
}