tcpClient.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const Socket = require("net").Socket;
  2. const TextEncoder = require("util").TextEncoder;
  3. const sleep = require("../utils/Helpers").helpers.sleep;
  4. class TcpClient {
  5. constructor() {
  6. this.connected = false;
  7. this.socket = new Socket();
  8. this.canceled = false;
  9. this.delay = 100;
  10. }
  11. /**
  12. * Connects to the specified IP and port number
  13. * @param ip
  14. * @param port
  15. */
  16. async connect(ip, port) {
  17. this.socket.connect({host: ip, port: port});
  18. this.connected = true;
  19. }
  20. /**
  21. * Closes the connection
  22. */
  23. async close() {
  24. this.socket.destroy();
  25. this.connected = true;
  26. }
  27. /**
  28. * Writes (sends) the specified bytes to the connected peer
  29. * @param data
  30. */
  31. async write(data) {
  32. this.socket.write(data);
  33. }
  34. /**
  35. * Reads (receives) the specified bytes from the connected peer
  36. * @param bufferSize
  37. * @returns {Buffer}
  38. */
  39. async read(bufferSize) {
  40. this.canceled = false;
  41. let buffer = Buffer.alloc(0);
  42. let writtenCount = 0;
  43. while (writtenCount < bufferSize) {
  44. let leftCount = bufferSize - writtenCount;
  45. let partial = this.socket.read(leftCount);
  46. if (partial == null) {
  47. await sleep(this.delay);
  48. continue;
  49. }
  50. buffer = Buffer.concat([buffer, partial]);
  51. writtenCount += buffer.byteLength;
  52. }
  53. return buffer;
  54. }
  55. /**
  56. * Cancels the read operation IF it hasn't yet
  57. * started, raising a ReadCancelledError
  58. */
  59. cancelRead() {
  60. this.canceled = true;
  61. }
  62. }
  63. exports.TcpClient = TcpClient;