下面是如何从节点net docs创建TCP客户端连接的示例(
https://nodejs.org/api/net.html#net_net_connect_options_connectlistener
)
const client = net.createConnection({ port: 1905 }, () => {
// 'connect' listener
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
如果服务器不可用,我会
Error: connect ECONNREFUSED 127.0.0.1:1905
.
在服务器可用之前等待/重新连接,并在服务器可用时进行连接,而不是抛出错误,有什么好方法?
编辑:这里有一个我已经尝试过的替代方法,但这里有个问题
MaxListeners超出警告:可能的EventEmitter内存泄漏
检测。增加了11个连接监听器。使用emitter.setMaxListeners()到
增长极限
我希望最新的侦听器替换较早的侦听器。他们都听同样的话。我只想再试一次。
function initTcpClient() {
console.log("Initiating TCP client...")
var tcpSocket = new net.Socket();
const client = net.createConnection({ port: 1905 }, () => {
tcpSocket.on('error', function onError(err) {
setTimeout(connect, 1000);
});
connect();
function connect() {
console.log("Looking for TCP server...");
tcpSocket.connect(argv.tcpport, argv.tcphost, function onConnected() {
console.log("Connecting to TCP server...");
tcpSocket.on('data', function onIncoming(data) {
if (connectedWebsocketClient) {
console.log('Forwarding to WebSocket: %s', data);
webSocketClient.send(data.toString());
} else {
console.log('Not connected to websocket client. Dropping incoming TCP message: %s', data);
}
});
tcpSocket.on('close', function onClose(hadError) {
console.log("Connection to TCP server was closed.");
connectedToTcpServer = false;
setTimeout(connect, 1000);
});
console.log("Connected to TCP server.");
connectedToTcpServer = true;
});
}
}