This repository has been archived by the owner on Oct 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.js
80 lines (65 loc) · 1.87 KB
/
chat.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// This code is based a bit upon different chat servers I found on the interwebz.
// Thanks for the ones that uploaded examples that I could base this upon.
// NOTE: Not totally commented yet, but schat.js is a bit similar so you could take a look at that to see if it helps
// Includes neccecary modules
var net = require("net");
Array.prototype.remove = function(e) {
for (var i = 0; i < this.length; i++) {
if (e == this[i]) { return this.splice(i, 1); }
}
};
function Client(stream) {
this.name = null;
this.stream = stream;
}
var clients = [];
var server = net.createServer(function (stream) {
var client = new Client(stream);
stream.setTimeout(0);
stream.setEncoding("utf8");
clients.push(client);
stream.addListener("connect", function () {
stream.write("Welcome, enter your username: ");
});
stream.addListener("data", function (data) {
if (client.name == null) {
client.name = data.match(/\S+/);
stream.write("===========\n");
clients.forEach(function(c) {
if (c != client) {
c.stream.write(client.name + " has joined.\n");
}
});
return;
}
var command = data.match(/^\/(.*)/);
if (command) {
var commandParameters = command[1].split(/[\s,]+/);
if (command[1] == 'users') {
clients.forEach(function(c) {
stream.write("- " + c.name + "\n");
});
}
else if (command[1] == 'quit') {
stream.end();
} else if (commandParameters[0] == 'username'){
client.name = commandParameters[1].match(/\S+/);
stream.write("Changed to "+commandParameters[1]+"\n");
}
return;
}
clients.forEach(function(c) {
if (c != client) {
c.stream.write("\033[32m"+client.name + "\033[39m > " + data);
}
});
});
stream.addListener("end", function() {
clients.remove(client);
clients.forEach(function(c) {
c.stream.write(client.name + " has left.\n");
});
stream.end();
});
});
server.listen(7000);