From 928dad71b935bab6a4c8e57c06868e379b0bedcf Mon Sep 17 00:00:00 2001 From: zhangbk1 Date: Mon, 4 Sep 2023 11:35:07 +0800 Subject: [PATCH] add TCP Server - with retry (node demo) --- .../tcp-server-node-demo-with-retry.js | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 tools/server-client/tcp-server-node-demo-with-retry.js diff --git a/tools/server-client/tcp-server-node-demo-with-retry.js b/tools/server-client/tcp-server-node-demo-with-retry.js new file mode 100644 index 0000000..c7c8e34 --- /dev/null +++ b/tools/server-client/tcp-server-node-demo-with-retry.js @@ -0,0 +1,61 @@ +/** + * TCP Server - with retry (node demo) + * CommonJS + */ +// 引入net模块 +var net = require('net'); + +const port = 3000 + +// 定义一个延迟时间 +const delay = 5000; + +// 定义create()方法,创建一个tcp服务端 +function create() { + // 创建一个tcp服务端对象 + var server = net.createServer(); + + // 监听连接事件 + server.on('connection', function (socket) { + // 打印客户端地址和端口号 + console.log('客户端已连接,地址:' + socket.remoteAddress + ',端口:' + socket.remotePort); + + // 监听数据事件 + socket.on('data', function (data) { + // 打印接收到的消息 + console.log('接收到消息:' + data.toString()); + }); + + // 监听错误事件 + socket.on('error', function (err) { + // 打印错误信息 + console.log('发生错误:' + err.message); + // 关闭连接 + socket.destroy(); + // 释放资源 + socket.unref(); + }); + }); + + // 监听错误事件 + server.on('error', function (err) { + // 打印错误信息 + console.log('发生错误:' + err.message); + // 关闭服务端 + server.close(); + // 释放资源 + server.unref(); + + console.log('尝试重新创建服务端'); + // 设置一个延迟时间后重新创建服务端 + setTimeout(create, delay); + }); + + // 监听端口 + server.listen(port, function () { + console.log('服务端已启动,监听端口: ' + port); + }); +} + +// 调用create()方法,启动服务端 +create(); \ No newline at end of file