var net = require('net'); var ClientConnection = require('./ClientConnection.js'); var config = {"socketTimeout":3000, "port": 30000} net.createServer(function(socket) {var clientConnection = new ClientConnection(socket, config);}) .listen(config.port, function () {console.log('Listening on: ' + config.port);});
var ClientConnection = function (socket, config){...}
ClientConnection.prototype.to = function (newState) { // onExitHandler? if (this.currentState && this.states[this.currentState].onExitHandler && typeof this.states[this.currentState].onExitHandler == 'function') { this.states[this.currentState].onExitHandler.call(this); } var prevState = this.currentState; this.currentState = newState; // inputHandler? if (this.currentState && this.states[this.currentState].inputHandler && typeof this.states[this.currentState].inputHandler == 'function') { this.handleInput = this.states[this.currentState].inputHandler.bind(this); } else { this.handleInput = this.noInputHandler } // onEnterHandler? if (this.states[this.currentState].onEnterHandler && typeof this.states[this.currentState].onEnterHandler == 'function') { this.states[this.currentState].onEnterHandler.call(this, prevState); } return this; }
ClientConnection.prototype.states = { 'inital': { 'onEnterHandler': function(){ // socket events this.socket.on('timeout', function() {this.to('socket-timeout');}.bind(this)); this.socket.on('end', function() {this.to("socket-end");}.bind(this)); this.socket.on('error', function (exc) {this.to("socket-error").handleInput(exc);}.bind(this)); this.socket.on('close', function () {this.to("socket-close");}.bind(this)); this.socket.on('data', function (data) {this.handleInput(data);}.bind(this)); this.to("waitingForHelloFromClient"); } }, ... }
Source: https://habr.com/ru/post/272983/
All Articles