获取连接关闭时socket的有关信息

来源:互联网 发布:柬埔寨经济指标数据图 编辑:程序博客网 时间:2024/06/04 23:19
当net.Socket被关闭的时候,按照通常的做法无法在"error"或者"close"事件中取得被关闭的那个socket的有关信息,例如:
sock.on("close",function(){
//console.log(sock.remoteAddress + ": " + sock.remotePort + " exit!");
);
对于上述代码,sock.remoteAddress和sock.remotePort将是undefined.之所以这样并不是因为这个时候sock对象已经完全被销毁了。因为如果此时在"close"事件的回调函数中直接打印出sock的值,发现内容将是这样:
{ _connecting: false,
_handle: null,
_readableState:
{ highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: false,
ended: false,
endEmitted: false,
reading: true,
calledRead: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
objectMode: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: false,
domain: null,
_events:
{ end: [ [Object], [Function] ],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
data: [Function],
readable: [Function],
close: [Function],
error: [Function] },
_maxListeners: 10,
_writableState:
{ highWaterMark: 16384,
objectMode: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
errorEmitted: true },
writable: false,
allowHalfOpen: false,
onend: null,
destroyed: true,
bytesRead: 508,
_bytesDispatched: 659,
_pendingData: null,
_pendingEncoding: '',
server:
{ domain: null,
_events: { connection: [Function], error: [Function], close: [Function]
_maxListeners: 10,
_connections: 0,
connections: [Getter/Setter],
_handle:
{ fd: null,
writeQueueSize: 0,
onconnection: [Function: onconnection],
owner: [Circular] },
_usingSlaves: false,
_slaves: [],
allowHalfOpen: false,
_connectionKey: '4:0.0.0.0:4448' },
_peername: { address: '192.168.1.6', family: 'IPv4', port: 9295 },
pipe: [Function],
addListener: [Function: addListener],
on: [Function: addListener],
pause: [Function],
resume: [Function],
read: [Function],
_consuming: true,
_idleNext: null,
_idlePrev: null,
_idleTimeout: -1 }
其中_peername对象就保存了被关闭的那个socket的网络节点!

这是基于TCP的socket对象,而UDP的属性就要比TCP的少很多:
{ domain: null,
_events: { error: [Function], listening: [Function], message: [Function] },
_maxListeners: 10,
_handle:
{ fd: null,
lookup: [Function: lookup4],
owner: [Circular],
onmessage: [Function: onMessage] },
_receiving: true,
_bindState: 2,
type: 'udp4',
fd: -42 }
0 0
原创粉丝点击