tcpClient.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. console.log("sleeping");
  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. module.exports = TcpClient;