index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. const net = require('net');
  2. const readline = require('readline');
  3. const HOST = 'localhost';
  4. const PORT = 6667;
  5. const sessions = new Set();
  6. function randomNick(len = 8) {
  7. let nick = '';
  8. for (let i = 0; i < len; i++) {
  9. nick += String.fromCharCode(97 + Math.floor(Math.random() * 26));
  10. }
  11. return nick;
  12. }
  13. function createSession() {
  14. const nick = randomNick();
  15. const socket = net.createConnection({ host: HOST, port: PORT });
  16. let buffer = '';
  17. const session = { socket, nick };
  18. socket.on('connect', () => {
  19. socket.write(`NICK ${nick}\r\n`);
  20. socket.write(`USER ${nick} 0 * :${nick}\r\n`);
  21. console.log(`[+] Connected: ${nick}`);
  22. });
  23. socket.on('data', (data) => {
  24. buffer += data.toString();
  25. let lines = buffer.split('\r\n');
  26. buffer = lines.pop();
  27. for (const line of lines) {
  28. if (line.startsWith('PING')) {
  29. const token = line.slice(5);
  30. socket.write(`PONG ${token}\r\n`);
  31. }
  32. }
  33. });
  34. socket.on('close', () => {
  35. console.log(`[-] Disconnected: ${nick}`);
  36. sessions.delete(session);
  37. });
  38. socket.on('error', (err) => {
  39. console.log(`[!] Error (${nick}): ${err.message}`);
  40. });
  41. sessions.add(session);
  42. return session;
  43. }
  44. function destroySession(session) {
  45. session.socket.destroy();
  46. sessions.delete(session);
  47. }
  48. function setCount(target) {
  49. const current = sessions.size;
  50. if (target > current) {
  51. for (let i = 0; i < target - current; i++) createSession();
  52. } else if (target < current) {
  53. const toRemove = [...sessions].slice(target);
  54. for (const s of toRemove) destroySession(s);
  55. }
  56. }
  57. function sendAll(message) {
  58. for (const s of sessions) {
  59. s.socket.write(`${message}\r\n`);
  60. }
  61. }
  62. // Start with one connection
  63. createSession();
  64. const rl = readline.createInterface({ input: process.stdin });
  65. rl.on('line', (line) => {
  66. line = line.trim();
  67. if (!line) return;
  68. if (line === 'exit') {
  69. for (const s of [...sessions]) destroySession(s);
  70. process.exit(0);
  71. }
  72. const num = Number(line);
  73. if (!isNaN(num) && line !== '') {
  74. setCount(Math.max(0, Math.floor(num)));
  75. console.log(`[*] Sessions: ${sessions.size}`);
  76. } else {
  77. sendAll(line);
  78. console.log(`[>] Sent to ${sessions.size} session(s): ${line}`);
  79. }
  80. });
  81. rl.on('close', () => {
  82. for (const s of [...sessions]) destroySession(s);
  83. process.exit(0);
  84. });