我正在程序中保存连接/套接字对象,如下所示:
var clients = [];
net.createServer(function (socket) {
clients.push(socket);
//morecode...
稍后在代码中我使用该数组来广播消息:
function broadcast(message, sender) {
clients.forEach(function (client) {
client.write(message);
});
}
到目前为止非常简单。现在,我想在我的mongodb服务器中保存套接字变量,以便我可以从我的服务器应用程序的不同实例访问它。我的第一个方法是做类似的事情:
var client = new Client({
name: socket.remoteAddress + ":" + socket.remotePort,
socket: JSON.stringify(socket)
});
client.save(function (err) {
if (err)
console.log(err);
});
但我得到了: TypeError:将循环结构转换为JSON 我在SO中从类似问题得到的建议是使用util.inspect,我可以设法保存套接字var的字符串表示形式:
的console.log(插座)
Socket {
_connecting: false,
_hadError: false,
_handle:
TCP {
_externalStream: {},
fd: 14,
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0 },
_parent: null,
_host: null,
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: true,
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: { [Function: g] listener: [Function: onend] },
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd] },
_eventsCount: 3,
_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: false,
errorEmitted: false },
writable: true,
allowHalfOpen: false,
destroyed: false,
bytesRead: 0,
_bytesDispatched: 0,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server:
Server {
domain: null,
_events: { connection: [Function] },
_eventsCount: 1,
_maxListeners: undefined,
_connections: 1,
_handle:
TCP {
_externalStream: {},
fd: 12,
reading: false,
owner: [Circular],
onread: null,
onconnection: [Function: onconnection],
writeQueueSize: 0 },
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: false,
pauseOnConnect: false,
_connectionKey: '6::::5000' } }
的console.log(util.inspect(插座))
{socket:'Socket {\ n _connecting: false,\ n _hadError:false,\ n _handle:\ n TCP {\ n
_externalStream:{},\ n fd:14,\ n读取:true,\ n所有者:[循环],\ n onread:[功能:onread],\ n onconnection: null,\ n writeQueueSize:0},\ n _parent:null,\ n _host:null,\ n _readableState:\ n ReadableState {\ n objectMode:false,\ n highWaterMark:16384,\ n buffer:[],\ n length:0,\ n pipes: null,\ n pipesCount:0,\ n flows:null,\ n结束:false,\ n endEmitted:false,\ n读取:true,\ n sync:false,\ n
needReadable:true,\ n emitseReadable:false,\ n
readableListening:false,\ n resumeScheduled:false,\ n
defaultEncoding:\'utf8 \',\ n ranOut:false,\ n awaitDrain:0,\ n readingMore:false,\ n decoder:null,\ n encoding:null},\ n 可读:true,\ n domain:null,\ n _events:\ n {end:{[功能: g]监听器:[功能:一次]},\ n完成:[功能: onSocketFinish],\ n _socketEnd:[Function:onSocketEnd]},\ n _eventsCount:3,\ n _maxListeners:undefined,\ n _writableState:\ n WritableState {\ n objectMode:false,\ n highWaterMark:16384,\ n needDrain:false,\ n结尾:false,\ n结束:false,\ n
finished:false,\ n decodeStrings:false,\ n defaultEncoding: \'utf8 \',\ n长度:0,\ n写入:false,\ n corked:0,\ n
sync:true,\ n bufferProcessing:false,\ n onwrite: [功能],\ n writecb:null,\ n writelen:0,\ n
bufferedRequest:null,\ n lastBufferedRequest:null,\ n
pendingcb:0,\ n prefinished:false,\ n errorEmitted:false},\ n writable:true,\ n allowHalfOpen:false,\ n destroy:false,\ n bytesRead:0,\ n _bytesDispatched:0,\ n _sockname:null,\ n _pendingData:null,\ n _pendingEncoding:\'\',\ n server:\ n Server {\ n domain:null,\ n _events:{connection:[Function]},\ n
_eventsCount:1,\ n _maxListeners:undefined,\ n _connections:1,\ n _handle:\ n TCP {\ n _externalStream:{},\ n
fd:12,\ n阅读:false,\ n所有者:[通告],\ n
onread:null,\ n onconnection:[Function:onconnection],\ n
writeQueueSize:0},\ n _usingSlaves:false,\ n _slaves:[],\ n
_unref:false,\ n allowHalfOpen:false,\ n pauseOnConnect:false,\ n _connectionKey:\'6 :::: 5000 \'},\ n _peername:{地址: \':: ffff:XXXXXXX \',系列:\'IPv6 \',端口:1145},\ n'}'}
在那种形式下,我可以将它保存到mongodb,但我不知道如何将其重新转换为socket对象nodejs可以使用。
答案 0 :(得分:0)
Another work around解决TypeError: Converting circular structure to JSON
,自定义JSON.stringify
,如下所示
var cache = [];
var obj = JSON.stringify(sock, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
cache = null; // Enable garbage collection
console.log(obj);
因此很容易通过JSON.parse
console.log(JSON.parse(obj));