实现思路
- 使用
net
模块创建TCP客户端。
- 通过
connect
方法尝试与服务器建立连接。
- 使用
setTimeout
设置连接超时,若在规定时间内未成功连接,则关闭连接并处理超时逻辑。
代码示例
const net = require('net');
const client = new net.Socket();
const host = '127.0.0.1'; // 服务器IP
const port = 8080; // 服务器端口
const timeout = 5000; // 5秒超时
let timeoutTimer;
client.connect(port, host, () => {
clearTimeout(timeoutTimer);
console.log('Connected to server');
});
timeoutTimer = setTimeout(() => {
client.destroy();
console.log('Connection timed out');
}, timeout);
client.on('error', (err) => {
clearTimeout(timeoutTimer);
console.log('Connection error: ', err.message);
});