tcpClient.js 1.6 KB

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