这个小测试脚本显示了我的问题。它会发送消息,关闭所有套接字,然后等待,永不退出。假设将ZMQ_LINGER设置为0应该使其立即丢弃所有排队的消息,那么为什么这不允许我的Node.js进程退出?
const zmq = require('zmq')
const bindUrl = 'tcp://127.0.0.1:4000'
let timer
let publisher = zmq.socket('pub')
publisher.monitor(500, 0)
publisher.setsockopt(zmq.ZMQ_LINGER, 0)
publisher.bind(bindUrl)
let subscriber = zmq.socket('sub')
subscriber.monitor(500, 0)
subscriber.setsockopt(zmq.ZMQ_LINGER, 0)
subscriber.connect(bindUrl)
subscriber.on('connect_error', () => {
console.log('connect error')
})
subscriber.on('connect', () => {
subscriber.subscribe('some topic')
})
publisher.on('bind', function () {
console.log('bound')
timer = setInterval(() => publisher.send(['some topic', 'blah']), 1000)
})
publisher.on('bind_error', function () {
console.log('bind error')
})
subscriber.on('disconnect', function () {
console.log('subscriber disconnected')
subscriber.close()
})
subscriber.on('close', function () {
console.log('subscriber closed')
subscriber.removeAllListeners()
subscriber = null
})
publisher.on('unbind', function () {
console.log('publisher unbound')
publisher.close()
})
publisher.on('close', function () {
console.log('publisher closed')
publisher.removeAllListeners()
publisher = null
subscriber.disconnect(bindUrl)
})
subscriber.on('message', function (topic, message) {
console.log(topic.toString(), message.toString())
clearInterval(timer)
subscriber.unsubscribe('some topic')
publisher.unbind(bindUrl)
})
输出如下,进程永不退出。
erin@titania:~/$ node test-disconnect.js
bound
some topic blah
publisher unbound
publisher closed
subscriber disconnected
subscriber closed
答案 0 :(得分:1)
我明确监视套接字的原因是导致此行为的原因。当我准备让进程退出时,我必须明确地调用socket.unmonitor
。