server.js 850 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. const net = require('net');
  3. const EventEmitter = require('events').EventEmitter;
  4. const Connection = require('./connection');
  5. const ConnectionConfig = require('./connection_config');
  6. // TODO: inherit Server from net.Server
  7. class Server extends EventEmitter {
  8. constructor() {
  9. super();
  10. this.connections = [];
  11. this._server = net.createServer(this._handleConnection.bind(this));
  12. }
  13. _handleConnection(socket) {
  14. const connectionConfig = new ConnectionConfig({
  15. stream: socket,
  16. isServer: true
  17. });
  18. const connection = new Connection({ config: connectionConfig });
  19. this.emit('connection', connection);
  20. }
  21. listen(port) {
  22. this._port = port;
  23. this._server.listen.apply(this._server, arguments);
  24. return this;
  25. }
  26. close(cb) {
  27. this._server.close(cb);
  28. }
  29. }
  30. module.exports = Server;