MST

星途 面试题库

面试题:Node.js TCP客户端如何处理连接超时

在Node.js进行TCP客户端开发时,假设要与服务器建立连接,且要求设置连接超时时间为5秒。请描述实现思路并给出相应代码示例。
10.2万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 使用net模块创建TCP客户端。
  2. 通过connect方法尝试与服务器建立连接。
  3. 使用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);
});