1 |
|
2 |
|
3 | import net from 'net';
|
4 | import superscript from 'superscript';
|
5 |
|
6 | const sockets = [];
|
7 |
|
8 | const botHandle = function botHandle(err, bot) {
|
9 | const receiveData = function receiveData(socket, bot, data) {
|
10 |
|
11 | let message = `${data}`;
|
12 |
|
13 | message = message.replace(/[\x0D\x0A]/g, '');
|
14 |
|
15 | if (message.indexOf('/quit') === 0 || data.toString('hex', 0, data.length) === 'fff4fffd06') {
|
16 | socket.end('Good-bye!\n');
|
17 | return;
|
18 | }
|
19 |
|
20 |
|
21 | bot.reply(socket.remoteAddress, message.trim(), (err, reply) => {
|
22 |
|
23 | const i = sockets.indexOf(socket);
|
24 | const soc = sockets[i];
|
25 |
|
26 | soc.write(`\nBot> ${reply.string}\n`);
|
27 | soc.write('You> ');
|
28 | });
|
29 | };
|
30 |
|
31 | const closeSocket = function closeSocket(socket, bot) {
|
32 | const i = sockets.indexOf(socket);
|
33 | const soc = sockets[i];
|
34 |
|
35 | console.log(`User '${soc.name}' has disconnected.\n`);
|
36 |
|
37 | if (i !== -1) {
|
38 | sockets.splice(i, 1);
|
39 | }
|
40 | };
|
41 |
|
42 | const newSocket = function newSocket(socket) {
|
43 | socket.name = `${socket.remoteAddress}:${socket.remotePort}`;
|
44 | console.log(`User '${socket.name}' has connected.\n`);
|
45 |
|
46 | sockets.push(socket);
|
47 |
|
48 |
|
49 | socket.write('Welcome to the Telnet server!\n');
|
50 | socket.write(`Hello ${socket.name}! ` + 'Type /quit to disconnect.\n\n');
|
51 |
|
52 |
|
53 | socket.write('You> ');
|
54 |
|
55 | socket.on('data', (data) => {
|
56 | receiveData(socket, bot, data);
|
57 | });
|
58 |
|
59 |
|
60 | socket.on('end', () => {
|
61 | closeSocket(socket, bot);
|
62 | });
|
63 | };
|
64 |
|
65 |
|
66 | const server = net.createServer(newSocket);
|
67 |
|
68 | server.listen(2000);
|
69 | console.log('TCP server running on port 2000.\n');
|
70 | };
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 | const options = {
|
77 | factSystem: {
|
78 | clean: true,
|
79 | },
|
80 | importFile: './data.json',
|
81 | };
|
82 |
|
83 | superscript.setup(options, (err, bot) => {
|
84 | botHandle(null, bot);
|
85 | });
|