-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcplistener.js
92 lines (79 loc) · 2.91 KB
/
tcplistener.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
81
82
83
84
85
86
87
88
89
90
91
92
var net = require('net');
var client_ctr = 0;
var server = net.createServer(function(socket){
/*socket.on('data', function(data)
{
console.log("Client command:" + data);
if(String(data).trim == "disconnect"){
console.log("Disconect Command Recieved");
socket.write("Disconecting. Have a nice day");
socket.close();
}
});*/
socket.on('data', function(data){
console.log("Client command: " + data);
if (String(data).trim() == "disconnect") {
console.log("Disconnect command received");
socket.write("Disconnecting. Have a nice day.\n");
socket.close();
}
else if (String(data).trim() == "server address") {
console.log("Server address request received");
address = server.address();
socket.write("address: " + address.address + " port: " + address.port + "\n");
}
else if (String(data).match(/add\(/i)) {
var vals = String(data).split(/,|\(|\)/);
var val1 = parseInt(vals[1]);
var val2 = parseInt(vals[2]);
if(testInts(val1,val2))
socket.write('Result: ' + (val1+val2) + '\n');
else sendIntError(socket);
}
else if (String(data).match(/subtract\(/i)) {
var vals = String(data).split(/,|\(|\)/);
var val1 = parseInt(vals[1]);
var val2 = parseInt(vals[2]);
if(testInts(val1,val2))
socket.write('Result: ' + (val1-val2) + '\n');
else sendIntError(socket);
}
else if (String(data).match(/multiply\(/i)) {
var vals = String(data).split(/,|\(|\)/);
var val1 = parseInt(vals[1]);
var val2 = parseInt(vals[2]);
if(testInts(val1,val2))
socket.write('Result: ' + (val1*val2) + '\n');
else sendIntError(socket);
}
else if (String(data).match(/divide\(/i)) {
var vals = String(data).split(/,|\(|\)/);
var val1 = parseInt(vals[1]);
var val2 = parseInt(vals[2]);
if(testInts(val1,val2))
socket.write('Result: ' + (val1/val2) + '\n');
else sendIntError(socket);
}
else socket.write("Unknown command: " + data)
});
function sendIntError(socket) {
socket.write('Error: Values must be integers\n')
}
function testInts(val1, val2) {
if(!isInt(val1) || !isInt(val2)) return false;
return true;
}
// test whether a value is an integer
function isInt(val){
// parse value for int and float will be the same if the value is actually an int
if((parseFloat(val) == parseInt(val)) && !isNaN(val)){
return true;
} else {
return false;
}
}
client_ctr++;
console.log("Client " + client_ctr + " connected");
socket.write("Connected to server.\r\n");
});
server.listen(8080, "127.0.0.1");