telnet.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import EventEmitter from 'node:events'
  2. import net from 'node:net'
  3. import {TelnetInterface} from 'tui-lib/util/interfaces'
  4. import setupClient from './client.js'
  5. export default class TelnetServer extends EventEmitter {
  6. constructor(backend) {
  7. super()
  8. this.backend = backend
  9. this.server = new net.Server(socket => this.handleConnection(socket))
  10. this.sockets = []
  11. }
  12. listen(port) {
  13. this.server.listen(port)
  14. }
  15. async handleConnection(socket) {
  16. const telnetInterface = new TelnetInterface(socket)
  17. const { appElement, cleanTerminal, flushable } = await setupClient({
  18. backend: this.backend,
  19. writable: socket,
  20. screenInterface: telnetInterface,
  21. appConfig: {
  22. canControlPlayback: false,
  23. canControlQueue: true,
  24. canControlQueuePlayers: false,
  25. canProcessMetadata: false,
  26. canSuspend: false,
  27. showTabberPane: true,
  28. stopPlayingUponQuit: false,
  29. menubarColor: 2
  30. }
  31. })
  32. appElement.attachAsServerClient(this)
  33. let closed = false
  34. const quit = (msg = 'See you!') => {
  35. cleanTerminal()
  36. telnetInterface.cleanTelnetOptions()
  37. socket.write('\r' + msg + '\r\n')
  38. socket.end()
  39. flushable.end()
  40. closed = true
  41. this.sockets.splice(this.sockets.indexOf(socket), 1)
  42. }
  43. appElement.on('quitRequested', quit)
  44. socket.on('close', () => {
  45. if (!closed) {
  46. flushable.end()
  47. closed = true
  48. this.sockets.splice(this.sockets.indexOf(socket), 1)
  49. }
  50. this.emit('left', socket)
  51. })
  52. socket.quit = quit
  53. this.sockets.push(socket)
  54. this.emit('joined', socket)
  55. }
  56. disconnectAllSockets(msg) {
  57. while (this.sockets.length) {
  58. this.sockets[0].quit(msg)
  59. }
  60. }
  61. }