-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathServer.js
More file actions
89 lines (69 loc) · 1.96 KB
/
Server.js
File metadata and controls
89 lines (69 loc) · 1.96 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
83
84
85
86
87
88
89
'use strict';
// Load the TCP Library
const net = require('net');
// importing Client class
const Client = require('./Client');
class Server {
constructor (port, address) {
this.port = port || 5000;
this.address = address || '127.0.0.1';
// Array to hold our currently connected clients
this.clients = [];
}
/*
* Broadcasts messages to the network
* The clientSender doesn't receive it's own message
*/
broadcast (message, clientSender) {
this.clients.forEach((client) => {
if (client === clientSender)
return;
client.receiveMessage(message);
});
console.log(message.replace(/\n+$/, ""));
}
/*
* Starting the server
* The callback is executed when the server finally inits
*/
start (callback) {
var server = this;
this.connection = net.createServer((socket) => {
var client = new Client(socket);
// Validation, if the client is valid
if (!server._validateClient(client)) {
client.socket.destroy();
return;
}
// Broadcast the new connection
server.broadcast(`${client.name} connected.\n`, client);
// Storing client for later usage
server.clients.push(client);
// Triggered on message received by this client
socket.on('data', (data) => {
// Broadcasting the message
server.broadcast(`${client.name} says: ${data}`, client);
});
// Triggered when this client disconnects
socket.on('end', () => {
// Removing the client from the list
server.clients.splice(server.clients.indexOf(client), 1);
// Broadcasting that this player left
server.broadcast(`${client.name} disconnected.\n`);
});
});
// starting the server
this.connection.listen(this.port, this.address);
// setuping the callback of the start function
if (callback != undefined) {
this.connection.on('listening', callback);
}
}
/*
* An example function: Validating the client
*/
_validateClient (client){
return client.isLocalHost();
}
}
module.exports = Server;