I am having trouble initializing a tree of parent-child socket.io servers. The goal is for each node to be able to dispatch commands (emit events) to its parent node or to a child node. I will reproduce the code and then describe the issues more below.
import { Server } from 'socket.io';
import {io as client } from 'socket.io-client';
import { get_ip } from './utils.mjs' // return LAN IP as string
export class Node {
constructor(port) {
this[_parent_client] = null;
this[_child_clients] = [];
this[_server] = new Server();
this[_server].listen(port);
this[_addr] = `${get_ip()}:${port}`;
this[_server].on('connection', (socket) => {
socket.on('init_child', (addr) => {
this[_child_clients].unshift(new client('http://' + addr));
}
}
}
init_parent(addr) {
this[_parent_client] = new client('http://' + addr);
this[_parent_client].emit('init_child', this[_addr]);
}
}
Here is an example test that illustrates the problem:
import { Node } from '../Node.mjs';
import { get_ip } from '../utils.mjs';
const node1 = new Node(3000);
const node2 = new Node(3030);
node2.init_parent(get_ip() + ':3000');
console.log(node1[_child_clients]) // []
setTimeout(() => {
console.log(node1[_child_clients]); // prints Socket object
}, 1000);
I would like to not return from the init_parent
method until the init_child
event has been completely handled to prevent these sort of issues, but I'm not sure what the best way would be. I know I could simply put a no-op timeout in init_parent
since in this context, adding a new child node to the tree would be a rare event, so I guess my question is more on the conceptual side of distributed system design with this event-driven NodeJS architecture. What I envision is that the init_child
event should send some sort of acknowledgement to the new child client server after it is created and once the acknowledgement is received by the child we can return from the init_parent
function.
question from:
https://stackoverflow.com/questions/66060792/parent-child-node-initialization-with-nodejs-socket-io 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…