PromisedNetSockets.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. const Socket = require('net').Socket
  2. const closeError = new Error('NetSocket was closed')
  3. class PromisedNetSockets {
  4. constructor() {
  5. this.client = null
  6. this.closed = true
  7. }
  8. async read(number) {
  9. if (this.closed) {
  10. console.log('couldn\'t read')
  11. throw closeError
  12. }
  13. const canWe = await this.canRead
  14. const toReturn = this.stream.slice(0, number)
  15. this.stream = this.stream.slice(number)
  16. if (this.stream.length === 0) {
  17. this.canRead = new Promise((resolve) => {
  18. this.resolveRead = resolve
  19. })
  20. }
  21. return toReturn
  22. }
  23. async readAll() {
  24. if (this.closed || !await this.canRead) {
  25. throw closeError
  26. }
  27. const toReturn = this.stream
  28. this.stream = Buffer.alloc(0)
  29. this.canRead = new Promise((resolve) => {
  30. this.resolveRead = resolve
  31. })
  32. return toReturn
  33. }
  34. /**
  35. * Creates a new connection
  36. * @param port
  37. * @param ip
  38. * @returns {Promise<void>}
  39. */
  40. async connect(port, ip) {
  41. this.stream = Buffer.alloc(0)
  42. this.client = new Socket()
  43. this.canRead = new Promise((resolve) => {
  44. this.resolveRead = resolve
  45. })
  46. this.closed = false
  47. return new Promise((resolve, reject) => {
  48. this.client.connect(port, ip, () => {
  49. this.receive()
  50. resolve(this)
  51. })
  52. this.client.on('error', reject)
  53. this.client.on('close', () => {
  54. if (this.client.closed) {
  55. this.resolveRead(false)
  56. this.closed = true
  57. }
  58. })
  59. })
  60. }
  61. write(data) {
  62. if (this.closed) {
  63. throw closeError
  64. }
  65. this.client.write(data)
  66. }
  67. async close() {
  68. await this.client.destroy()
  69. this.client.unref()
  70. this.closed = true
  71. }
  72. async receive() {
  73. this.client.on('data', async (message) => {
  74. const data = Buffer.from(message)
  75. this.stream = Buffer.concat([this.stream, data])
  76. this.resolveRead(true)
  77. })
  78. }
  79. }
  80. module.exports = PromisedNetSockets