connectionHandler.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //@flow
  2. import type { Socket } from "net";
  3. const countAndSlice = require("./utils/countAndSlice");
  4. // All connections stored by id
  5. const Connections = {};
  6. // List of operations should be executed
  7. const secureOp = ["ping", "close"];
  8. class Connection {
  9. id: number;
  10. socket: Socket;
  11. buffer: string;
  12. queue: string[];
  13. constructor(id: number, socket: Socket) {
  14. console.log("New connection", id);
  15. this.id = id;
  16. this.socket = socket;
  17. this.buffer = "";
  18. this.queue = [];
  19. Connections[id] = this;
  20. socket.on("data", data => {
  21. data = data.toString();
  22. this.buffer = this.buffer.concat(data);
  23. console.log("Buffer", this.buffer);
  24. let [arr, count] = countAndSlice(this.buffer);
  25. if (arr.length > count) {
  26. this.buffer = arr.pop();
  27. } else {
  28. this.buffer = "";
  29. }
  30. this.queue = this.queue.concat(arr);
  31. while (this.queue.length > 0) {
  32. let op = this.queue.shift();
  33. this.execute(op);
  34. }
  35. })
  36. socket.on("end", () => {
  37. this.end();
  38. });
  39. }
  40. execute(op: string) {
  41. if (secureOp.includes(op)) {
  42. // $FlowFixMe
  43. this[op]();
  44. } else {
  45. this.write("Unkown operator\n\r");
  46. }
  47. }
  48. // Session`s Operations
  49. ping() {
  50. this.write("pong\n\r");
  51. }
  52. close() {
  53. this.write("Closing connection\n\r");
  54. this.socket.end();
  55. }
  56. // Connection methods
  57. write(input: string | Buffer) {
  58. this.socket.write(input);
  59. }
  60. end() {
  61. delete Connections[id];
  62. console.log("Connection closed", this.id);
  63. }
  64. }
  65. let id = 0;
  66. function connectionHandler(socket: Socket) {
  67. id++;
  68. new Connection(id, socket);
  69. }
  70. module.exports = connectionHandler;