| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- //@flow
- import type { Socket } from "net";
- const countAndSlice = require("./utils/countAndSlice");
- // All connections stored by id
- const Connections = {};
- // List of operations should be executed
- 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)) {
- // $FlowFixMe
- this[op]();
- } else {
- this.write("Unkown operator\n\r");
- }
- }
- // Session`s Operations
- ping() {
- this.write("pong\n\r");
- }
- close() {
- this.write("Closing connection\n\r");
- this.socket.end();
- }
- // Connection methods
- 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;
|