-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (60 loc) · 1.82 KB
/
index.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
// dependencies
var net = require("net"),
readline = require("readline");
/**
* @class Client
* @param host {String} the host
* @param post {Integer} the port
*/
function Client(host, port){
this.host = host;
this.port = port;
}
/**
* @method start
* start the client
*/
Client.prototype.start = function(cb){
// create readline interface
var rl = readline.createInterface(process.stdin, process.stdout);
var self = this;
// create TCP client
var client = net.connect({host: this.host, port: this.port}, function(){
// write out connection details
console.log("Connected to %s:%d\n", self.host, self.port);
rl.on("line", function(d){
// send data to through the client to the host
client.write(d.trim()+"\n");
});
client.on("data", function(d){
// pause to prevent more data from coming in
process.stdin.pause();
// write out the data
process.stdout.write(d.toString());
process.stdin.resume();
});
client.on("close", function(){
// stop input
process.stdin.pause();
// end readline
process.stdout.write("\nconnection closed by foreign host.\n");
rl.close();
});
rl.on("SIGINT", function(){
// stop input
process.stdin.pause();
process.stdout.write("\nending session\n");
rl.close();
// close connection
client.end();
});
if (cb) cb(client, rl, process.stdin, process.stdout);
});
};
/**
* @function createClient
* creates a new client
*/
exports.createClient = function(host, port){
return new Client(host, port);
};