Node.JS 官方文档中并没有获取当前 socket 连接状态的说明。不过打印 socket 可以看出,可以通过 socket._handle 属性来判断,当socket end或 destroy后,此属性被设为null。
当建立tcp连接后 _handle 为 tcp 对象:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
bytesRead: 0,
_externalStream: {},
fd: -1,
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0 },
_parent: null,
_host: null,
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: false,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [ [Object], [Function: onEnd] ],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
connect: [ [Function: onConnect] ],
close: [Function: onClose],
data: [Function: onData],
drain: [Function: onDrain],
error: [Function: onError],
lookup: [Function: onLookup],
timeout: [Function: onTimeout] },
_eventsCount: 10,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: true,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: CorkedRequest { next: null, entry: null, finish: [Function] } },
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 0,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
read: [Function],
_consuming: true,
_idleNext: null,
_idlePrev: null,
_idleTimeout: -1,
_peername: null }当 close 或者未连接状态时, _handle 为 null
Socket {
connecting: false,
_hadError: false,
_handle: null,
_parent: null,
_host: null,
_readableState:回复 (0)
微信扫码 立即评论
