-
Notifications
You must be signed in to change notification settings - Fork 11
/
telnet.js
86 lines (60 loc) · 2.07 KB
/
telnet.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
// Run this and then telnet to localhost:2000 and chat with the bot
var net = require("net");
var superscript = require("superscript").default;
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/telnetbot');
var options = {};
var sockets = [];
options['mongoose'] = mongoose;
var botHandle = function(err, bot) {
var receiveData = function(socket, bot, data) {
// Handle incoming messages.
var message = "" + data;
message = message.replace(/[\x0D\x0A]/g, "");
if (message.indexOf("/quit") === 0 || data.toString('hex',0,data.length) === "fff4fffd06") {
socket.end("Good-bye!\n");
return;
}
// Use the remoteIP as the name since the PORT changes on ever new connection.
bot.reply(socket.remoteAddress, message.trim(), function(err, reply){
// Find the right socket
var i = sockets.indexOf(socket);
var soc = sockets[i];
soc.write("\nBot> " + reply.string + "\n");
soc.write("You> ");
});
};
var closeSocket = function(socket, bot) {
var i = sockets.indexOf(socket);
var soc = sockets[i];
console.log("User '" + soc.name + "' has disconnected.\n");
if (i != -1) {
sockets.splice(i, 1);
}
};
var newSocket = function (socket) {
socket.name = socket.remoteAddress + ":" + socket.remotePort;
console.log("User '" + socket.name + "' has connected.\n");
sockets.push(socket);
// Send a welcome message.
socket.write('Welcome to the Telnet server!\n');
socket.write("Hello " + socket.name + "! " + "Type /quit to disconnect.\n\n");
// Send their prompt.
socket.write("You> ");
socket.on('data', function(data) {
receiveData(socket, bot, data);
});
// Handle disconnects.
socket.on('end', function() {
closeSocket(socket, bot);
});
};
// Start the TCP server.
var server = net.createServer(newSocket);
server.listen(2000);
console.log("TCP server running on port 2000.\n");
};
// Main entry point
superscript.setup(options, function(err, botInstance){
botHandle(null, botInstance);
});