web3 websocket连接可防止节点进程退出

And*_*ang 9 javascript websocket ethereum solidity web3-donotuse

我有一个节点js进程,它创建一个web3 websocket连接,如下所示:

web3 = new Web3('ws://localhost:7545')
Run Code Online (Sandbox Code Playgroud)

当进程完成时(我发送一个SIGTERM),它不会退出,而是永远挂起而没有控制台输出.

我注册了SIGINT和SIGTERM一个听众在什么处理过程中具有突出以观察process._getActiveRequests()process._getActiveHandles(),我看到以下内容:

 Socket {
    connecting: false,
    _hadError: false,
    _handle: 
     TCP {
       reading: true,
       owner: [Circular],
       onread: [Function: onread],
       onconnection: null,
       writeQueueSize: 0 },
    <snip>
    _peername: { address: '127.0.0.1', family: 'IPv4', port: 7545 },
    <snip>
}
Run Code Online (Sandbox Code Playgroud)

为了完整性,这里是监听信号的代码:

async function stop() {
  console.log('Shutting down...')

  if (process.env.DEBUG) console.log(process._getActiveHandles())

  process.exit(0)
}

process.on('SIGTERM', async () => {
  console.log('Received SIGTERM')
  await stop()
})

process.on('SIGINT', async () => {
  console.log('Received SIGINT')
  await stop()
})
Run Code Online (Sandbox Code Playgroud)

看起来web3正在打开一个套接字,这是有道理的,因为我从未告诉它关闭连接.通过文档和谷歌搜索,它看起来不像web3对象的close或end方法.

手动关闭stop上面的套接字允许进程成功退出:

web3.currentProvider.connection.close()
Run Code Online (Sandbox Code Playgroud)

任何人都有更优雅或官方认可的解决方案?我觉得有必要手动执行此操作,而不是让对象在进程结束时自行销毁.其他客户端似乎自动执行此操作而未明确告知他们关闭其连接.也许告诉你的节点进程创建的所有客户端在关机时关闭他们的句柄/连接是更干净,但对我来说,这是意料之外的.

goo*_*ion 1

在 Node js 进程结束时,只需调用:

web3.currentProvider.connection.close()
Run Code Online (Sandbox Code Playgroud)