按照net和child_process模塊的官方節點檔案,我歸檔了這個:一個產生子節點并通過net模塊連接的服務器。但是連接是斷斷續續的。代碼是不言自明的,但我在代碼注釋中添加了詳細資訊:
// server.js
const childProcess = require('child_process').fork('child.js');
const server = require('net').createServer((socket) => {
console.log('got socket connection'); // this callback is intermitent
socket.on('data', (stream) => {
console.log(stream.toString());
})
});
server.on('connection', () => {
console.log('someone connected to server'); // this is running only if the code above runs (but its intermitent)
});
server.on('listening', () => {
console.log('server is listening'); // this is the first log to execute
childProcess.send('server', server); // send the server connection to forked child
});
server.listen(null, function () {
console.log('server listen callback'); // this is the second log to execute
});
// child.js
console.log('forked'); // this is the third log to execute
const net = require('net');
process.on('message', (m, server) => {
if (m === 'server') {
const socket = net.connect(server.address());
socket.on('ready', () => {
console.log('child is ready'); // this is the fourth log to execute
socket.write('child first message'); // this is always running
})
}
});
執行時的預期日志node server是:
server is listening
server listen callback
forked
child is ready
got socket connection
someone connected to server
child first message
但由于套接字回呼 (at createServer) 是間歇性的,我們有 50% 的機會得到這個:
server is listening
server listen callback
forked
child is ready
IDK該怎么辦了,已經嘗試了所有我能做的......我做錯了什么?
uj5u.com熱心網友回復:
剛剛發現問題是什么......當我閱讀檔案時,我誤解了net服務器被發送到子行程以共享“連接”以將處理劃分為多個行程,以及我試圖存檔的內容只是與分叉孩子的兩種方式交流。如果有人遇到與我相同的問題,我會在這里回答這個問題。這是最終的代碼:
// server.js
const childProcess = require('child_process').fork('child.js');
const server = require('net').createServer((socket) => {
console.log('got socket connection');
socket.on('data', (stream) => {
console.log(stream.toString());
})
});
server.on('connection', () => {
console.log('someone connected to server');
});
server.listen(null, function () {
childProcess.send(server.address());
});
// child.js
console.log('forked');
const net = require('net');
process.on('message', (message) => {
if (message.port) {
const socket = net.connect(message);
socket.on('ready', () => {
console.log('child is ready');
socket.write('child first message');
})
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/317919.html
標籤:javascript 节点.js 插座 工控机
上一篇:匯入pwn包時,pyinstaller未轉換(或生成損壞的exe)
下一篇:Flutter掃二維碼功能實作
