Browse Source

- Add Connection
- Moved connection handler to separate file
- Added "countAndSlice" function

Parad0x 7 năm trước cách đây
mục cha
commit
c6a1a447c0
3 tập tin đã thay đổi với 99 bổ sung8 xóa
  1. 77 1
      src/connectionHandler.js
  2. 2 7
      src/index.js
  3. 20 0
      src/utils/countAndSlice.js

+ 77 - 1
src/connectionHandler.js

@@ -2,8 +2,84 @@
 
 import type { Socket } from "net";
 
-function connectionHandler(socket: Socket) {
+const countAndSlice = require("./utils/countAndSlice");
+
+const Connections = {};
+
+const secureOp = ["ping", "close"];
+
+class Connection {
+  id: number;
+  socket: Socket;
+  buffer: string;
+  queue: string[];
+
+  constructor(id: number, socket: Socket) {
+    console.log("New connection", id);
+
+    this.id = id;
+    this.socket = socket;
+    this.buffer = "";
+    this.queue = [];
+
+    Connections[id] = this;
+
+    socket.on("data", data => {
+      data = data.toString();
+      this.buffer = this.buffer.concat(data);
+      console.log("Buffer", this.buffer);
+      let [arr, count] = countAndSlice(this.buffer);
+      if (arr.length > count) {
+        this.buffer = arr.pop();
+      } else {
+        this.buffer = "";
+      }
+      this.queue = this.queue.concat(arr);
+
+      while (this.queue.length > 0) {
+        let op = this.queue.shift();
+        this.execute(op);
+      }
+
+    })
 
+    socket.on("end", () => {
+      this.end();
+    });
+  }
+
+  execute(op: string) {
+    if (secureOp.includes(op)) {
+      this[op]();
+    } else {
+      this.write("Unkown operator\n\r");
+    }
+  }
+
+  ping() {
+    this.write("pong\n\r");
+  }
+
+  close() {
+    this.write("Closing connection\n\r");
+    this.socket.end();
+  }
+
+  write(input: string | Buffer) {
+    this.socket.write(input);
+  }
+
+  end() {
+    delete Connections[id];
+    console.log("Connection closed", this.id);
+  }
+}
+
+let id = 0;
+
+function connectionHandler(socket: Socket) {
+  id++;
+  new Connection(id, socket);
 }
 
 module.exports = connectionHandler;

+ 2 - 7
src/index.js

@@ -5,14 +5,9 @@ const path = require("path");
 const chalk = require("chalk");
 
 const socketPathCon = require("./utils/socketPath");
+const connectionHandler = require("./connectionHandler");
 
-let id = 0;
-
-const server = net.createServer(socket => {
-  id++;
-  console.log("Connected, id:", id);
-  socket.write("Test");
-});
+const server = net.createServer(connectionHandler);
 
 const socketPath = socketPathCon();
 

+ 20 - 0
src/utils/countAndSlice.js

@@ -0,0 +1,20 @@
+//@flow
+
+function countAndSlice(input: string, delimeter: string = ";"): [string[], number] {
+  let buff: string = "";
+  let arr: string[] = [];
+  let counter: number = 0;
+  for (let char of input) {
+    if (char == delimeter) {
+      counter++;
+      arr.push(buff);
+      buff = "";
+    } else {
+      buff = buff.concat(char);
+    }
+  }
+  arr.push(buff);
+  return [arr, counter];
+}
+
+module.exports = countAndSlice;