wsprocessor.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var HttpServer = require('http').Server;
  2. var EventEmitter = require('events').EventEmitter;
  3. var util = require('util');
  4. var WebSocketServer = require('ws').Server;
  5. var ST_STARTED = 1;
  6. var ST_CLOSED = 2;
  7. /**
  8. * websocket protocol processor
  9. */
  10. var Processor = function() {
  11. EventEmitter.call(this);
  12. this.httpServer = new HttpServer();
  13. var self = this;
  14. this.wsServer = new WebSocketServer({server: this.httpServer});
  15. this.wsServer.on('connection', function(socket) {
  16. // emit socket to outside
  17. self.emit('connection', socket);
  18. });
  19. this.state = ST_STARTED;
  20. };
  21. util.inherits(Processor, EventEmitter);
  22. module.exports = Processor;
  23. Processor.prototype.add = function(socket, data) {
  24. if(this.state !== ST_STARTED) {
  25. return;
  26. }
  27. this.httpServer.emit('connection', socket);
  28. if(typeof socket.ondata === 'function') {
  29. // compatible with stream2
  30. socket.ondata(data, 0, data.length);
  31. } else {
  32. // compatible with old stream
  33. socket.emit('data', data);
  34. }
  35. };
  36. Processor.prototype.close = function() {
  37. if(this.state !== ST_STARTED) {
  38. return;
  39. }
  40. this.state = ST_CLOSED;
  41. this.wsServer.close();
  42. this.wsServer = null;
  43. this.httpServer = null;
  44. };