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

当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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值