web3Ipc.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. const Q = require('bluebird');
  2. const net = require('net');
  3. const SocketBase = require('./base');
  4. const STATE = SocketBase.STATE;
  5. const Web3SocketBase = require('./web3Base');
  6. module.exports = class Web3IpcSocket extends Web3SocketBase {
  7. /**
  8. * Reset socket.
  9. */
  10. _resetSocket() {
  11. this._log.debug('Resetting socket');
  12. return Q.try(() => {
  13. if (STATE.CONNECTED === this._state) {
  14. this._log.debug('Disconnecting prior to reset');
  15. return this.disconnect();
  16. }
  17. }).then(() => {
  18. this._socket = new net.Socket();
  19. this._socket.setTimeout(0);
  20. this._socket.setEncoding('utf8');
  21. this._socket.unref(); /* allow app to exit even if socket fails to close */
  22. this._socket.on('close', hadError => {
  23. // if we did the disconnection then all good
  24. if (STATE.DISCONNECTING === this._state) {
  25. return;
  26. }
  27. this.emit('close', hadError);
  28. });
  29. this._socket.on('end', () => {
  30. this._log.debug('Got "end" event');
  31. this.emit('end');
  32. });
  33. this._socket.on('data', data => {
  34. this._log.trace('Got data');
  35. this.emit('data', data);
  36. });
  37. this._socket.on('timeout', () => {
  38. this._log.trace('Timeout');
  39. this.emit('timeout');
  40. });
  41. this._socket.on('error', err => {
  42. // connection errors will be handled in connect() code
  43. if (STATE.CONNECTING === this._state) {
  44. return;
  45. }
  46. this._log.error(err);
  47. this.emit('error', err);
  48. });
  49. });
  50. }
  51. };