在踩坑之旅(二)中,我提到了
net
模块中
Server
对象的
close
事件和同名方法以及
Socket
对象的
end
事件和同名方法。还有就是两者都有的
unref
方法。
而在Node.js的dgram
模块中定义的Socket
对象则具有close
事件和同名方法以及unref
方法。
不过与我写踩坑之旅(二)的原因一样,dgram
模块中定义的Socket
对象的close
事件和同名方法以及unref
方法,在作用上非常相似。
dgramSocketclose_7">dgram.Socket的close方法和事件
close事件
当调用Socket
对象的close
方法之后close
事件就会被触发。例如:
let dgram = require('dgram');
let socket = dgram.createSocket("udp4");
socket.on('close', ()=>{
console.log('Socket对象已关闭');
});
socket.close();
运行结果:
Socket
对象被关闭之后再调用它的其他方法都会报Not Running
的错误。
let dgram = require('dgram');
let udpServer = dgram.createSocket("udp4");
udpServer.on('message', (msg, rinfo)=>{
udpServer.close();
console.log(`客户端IP地址为${rinfo.address}`);
console.log('接收到的信息为:' + msg);
let sendMsg = new Buffer(msg);
udpServer.send(sendMsg, rinfo.port, rinfo.address, (err, bytes)=>{
if(err){
console.warn(err);
} else {
console.log(`发送${bytes}个字节的数据`);
}
});
});
udpServer.bind(2000);
udpServer.on('listening', ()=>{
let address = udpServer.address();
console.log('服务器开始监听,地址为:' + address);
});
例如上面的代码,执行后结果如下图:
dgramSocketunref_59">dgram.Socket的unref方法
By default, binding a socket will cause it to block the Node.js process from exiting as long as the socket is open. The socket.unref() method can be used to exclude the socket from the reference counting that keeps the Node.js process active, allowing the process to exit even if the socket is still listening.
以上摘自Node.js的官方文档关于unref
方法的介绍。这段话是说Socket
对象会阻止Node.js的进程退出,然而使用unref
方法可以让Socket
对象不进行引用计数。
换句话说,就是当执行了Sokcet
对象的unref
方法之后,当Socket
对象不再进行通信时,程序会退出。
值得注意的是这句话“ allowing the process to exit even if the socket is still listening”。就是说即使是Socket
对象还在监听数据,也允许退出。