From cc3a74468a9bbbb27ccebf30c27d60814a64468c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98=E5=B0=8F=E5=A2=A8?= <2291200076@qq.com> Date: Sat, 29 Jul 2023 22:28:21 +0800 Subject: [PATCH] =?UTF-8?q?server=20&=20client=20=E6=96=B0=E5=A2=9E=20&=20?= =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../http-server-node-demo.js} | 4 + .../tcp-server-node-demo.js} | 4 + tools/server-client/tcp-server-node-module.js | 106 +++++++++++++++ .../websocket-client-browser-demo.html} | 4 + .../websocket-client-node-demo-with-retry.js} | 3 +- .../websocket-client-node-demo.js} | 4 + .../websocket-client-node-module.js | 122 ++++++++++++++++++ 7 files changed, 246 insertions(+), 1 deletion(-) rename tools/{server/http-server.js => server-client/http-server-node-demo.js} (91%) rename tools/{server/tcp-server.js => server-client/tcp-server-node-demo.js} (92%) create mode 100644 tools/server-client/tcp-server-node-module.js rename tools/{client/websocket.test.html => server-client/websocket-client-browser-demo.html} (94%) rename tools/{client/node-websocket-client-with-retry.js => server-client/websocket-client-node-demo-with-retry.js} (93%) rename tools/{client/node-websocket-client.js => server-client/websocket-client-node-demo.js} (91%) create mode 100644 tools/server-client/websocket-client-node-module.js diff --git a/tools/server/http-server.js b/tools/server-client/http-server-node-demo.js similarity index 91% rename from tools/server/http-server.js rename to tools/server-client/http-server-node-demo.js index a442776..9104024 100644 --- a/tools/server/http-server.js +++ b/tools/server-client/http-server-node-demo.js @@ -1,3 +1,7 @@ +/** + * HTTP Server (node demo) + * CommonJS + */ const http = require('http'); const url = require('url'); diff --git a/tools/server/tcp-server.js b/tools/server-client/tcp-server-node-demo.js similarity index 92% rename from tools/server/tcp-server.js rename to tools/server-client/tcp-server-node-demo.js index f095259..deeac22 100644 --- a/tools/server/tcp-server.js +++ b/tools/server-client/tcp-server-node-demo.js @@ -1,3 +1,7 @@ +/** + * TCP Server (node demo) + * CommonJS + */ //引入net模块 const net = require('net'); //实例化一个服务器对象 diff --git a/tools/server-client/tcp-server-node-module.js b/tools/server-client/tcp-server-node-module.js new file mode 100644 index 0000000..3d6e98f --- /dev/null +++ b/tools/server-client/tcp-server-node-module.js @@ -0,0 +1,106 @@ +/** + * TCP Server (node export module) + * CommonJS + */ +//引入net模块 +const net = require('net') + +const LOG_DEBUG_INFO = false + +// 启动一个 TCP Server +const serverConfig = item.serverConfig +// 绑定 TCP Server 的 callback +tcpServer.createServer(serverConfig.port, { + onConnection: (socket, port) => { + // some code here ... + }, + onListening: (address, port, family) => { + // some code here ... + }, + onData: (data) => { + // some code here ... + }, + onClose: () => { + // some code here ... + }, + onError: (err) => { + // some code here ... + }, +}) + +module.exports = { + /** + * + * @param {*} port + * @param {*} param1 + * onConnection(socket, port) + * onListening(address, port, family) + * onData(data) + * onClose() + * onError(err) + */ + createServer(port, { onConnection, onListening, onData, onClose, onError }) { + LOG_DEBUG_INFO && console.log("启动 TCP 服务器") + //实例化一个服务器对象 + const server = new net.Server() + + //监听connection事件 + server.on('connection', function (socket) { + LOG_DEBUG_INFO && console.log('新客户端接入') + + //监听data事件 + socket.on("data", function (data) { + //打印数据 + LOG_DEBUG_INFO && console.log("接收到数据:[数据开始]" + data.toString() + "[数据结束]") + + if (typeof (onData) === "function") { + onData(data) + } + }); + + // 客户端 TCP 连接异常终止时,捕获该 error 并销毁该 socket,避免服务端异常退出 + socket.on('error', (err) => { + console.log('Socket error: ' + err); + // 这里可以根据错误类型进行不同的处理,例如关闭连接,重试,记录日志等 + socket.destroy(); + }); + + if (typeof (onConnection) === "function") { + onConnection(socket, port) + } + }) + + //设置监听端口 + server.listen(port) + + //设置监听时的回调函数 + server.on('listening', function () { + //获取地址信息 + let address = server.address() + //获取地址详细信息 + LOG_DEBUG_INFO && console.log(`TCP 服务器监听地址: ${address.address}, 端口: ${address.port}, 类型: ${address.family}`) + + if (typeof (onListening) === "function") { + onListening(address.address, address.port, address.family) + } + }) + + //设置关闭时的回调函数 + server.on('close', function () { + LOG_DEBUG_INFO && console.log('服务已关闭') + + if (typeof (onClose) === "function") { + onClose() + } + }) + + //设置出错时的回调函数 + server.on('error', function (err) { + LOG_DEBUG_INFO && console.log('服务运行异常', err) + + if (typeof (onError) === "function") { + onError(err) + } + }) + } +} \ No newline at end of file diff --git a/tools/client/websocket.test.html b/tools/server-client/websocket-client-browser-demo.html similarity index 94% rename from tools/client/websocket.test.html rename to tools/server-client/websocket-client-browser-demo.html index e28175d..23bb809 100644 --- a/tools/client/websocket.test.html +++ b/tools/server-client/websocket-client-browser-demo.html @@ -1,3 +1,7 @@ + diff --git a/tools/client/node-websocket-client-with-retry.js b/tools/server-client/websocket-client-node-demo-with-retry.js similarity index 93% rename from tools/client/node-websocket-client-with-retry.js rename to tools/server-client/websocket-client-node-demo-with-retry.js index a6a1b71..3f034b0 100644 --- a/tools/client/node-websocket-client-with-retry.js +++ b/tools/server-client/websocket-client-node-demo-with-retry.js @@ -1,5 +1,6 @@ /** - * node websocket server + * WebSocket Client - with retry (node demo) + * CommonJS */ // 引入websocket依赖 const WebSocket = require('websocket').client; diff --git a/tools/client/node-websocket-client.js b/tools/server-client/websocket-client-node-demo.js similarity index 91% rename from tools/client/node-websocket-client.js rename to tools/server-client/websocket-client-node-demo.js index 62d8721..5e477df 100644 --- a/tools/client/node-websocket-client.js +++ b/tools/server-client/websocket-client-node-demo.js @@ -1,3 +1,7 @@ +/** + * WebSocket Client (node demo) + * CommonJS + */ // 引入websocket依赖 const WebSocket = require('websocket').client; diff --git a/tools/server-client/websocket-client-node-module.js b/tools/server-client/websocket-client-node-module.js new file mode 100644 index 0000000..471f382 --- /dev/null +++ b/tools/server-client/websocket-client-node-module.js @@ -0,0 +1,122 @@ +/** + * WebSocket Client (node export module) + * CommonJS + */ +// 引入 +const WebSocket = require('websocket').client + +const LOG_PREFIX = "[websocket-client]" + +const PRINT_LOG = false + +function reconnect(client, url) { + // 打印一条重连消息 + console.log('Reconnecting to ' + url); + // 调用client的connect方法 + client.connect(url); +} + +function createConn(uniqueId, url, { onConnect, onMessage, onClose, onError }) { + PRINT_LOG && console.log(LOG_PREFIX, "createConn", uniqueId, url) + // 创建新的连接前先把旧的连接关掉 + // closeConn(uniqueId) + + let client = new WebSocket() + + // readyState返回当前实例对象的当前状态 + /* + 共有四种状态 + CONNECTING: 值为0,表示正在连接 + OPEN: 值为1,表示连接成功,可以通信了 + CLOSING 值为2, 表示连接正在关闭 + CLOSED 值为3,表示连接已经关闭了,或者打开连接失败 + */ + + client.on('connect', function (connection) { + // 连接成功后,打印一条消息 + console.log(LOG_PREFIX, 'Connected to ' + url); + + // callback + if (typeof (onConnect) === 'function') { + onConnect(connection) + } + + // 监听消息事件 + connection.on('message', function (message) { + // 收到消息后,打印出来 + let data = message.utf8Data + PRINT_LOG && console.log(LOG_PREFIX, 'Received: ' + data.substring(0, 20) + ' ...'); + + // callback + if (typeof (onMessage) === 'function') { + onMessage(data) + } + }); + + // 监听关闭事件 + connection.on('close', function (reasonCode, description) { + // 连接关闭后,打印一条消息 + console.log('Disconnected from ' + url); + + setTimeout(() => { // 重连 + reconnect(client, url) + }, 1000) + + // callback + if (typeof (onClose) === 'function') { + onClose() + } + }); + + // // 关闭连接 + // setTimeout(() => { + // connection.close() + // console.log("Close connection ...") + // }, 2000) + }); + + + // 监听错误事件 + client.on('connectFailed', function (error) { + // 连接失败后,打印一条错误信息 + console.error('Connect Error: ' + error.toString()); + + setTimeout(() => { // 重连 + reconnect(client, url) + }, 1000) + + // callback + if (typeof (onError) === 'function') { + onError(error) + } + }); + + client.connect(url) + + return client +} + +// async function sendMessage(uniqueId, message) { +// PRINT_LOG && console.log(LOG_PREFIX, "sendMessage", message) +// let data = JSON.stringify(message) +// if (wsInstance && wsInstance.send) { +// while (wsInstance && wsInstance.readyState != 1) { +// PRINT_LOG && console.warn("websocket 连接尚未准备好,等一会儿...", wsInstance.readyState) +// await new Promise((resolve) => setTimeout(resolve, 500)) +// } +// wsInstance.send(data) +// return +// } +// console.warn("wsInstance.sendMessage is not defined", wsInstance, wsInstance.send) + +// } + +// function closeConn(uniqueId) { +// wsInstance && wsInstance.close && wsInstance.close() +// } + +module.exports = { + createConn, + // sendMessage, + // closeConn, +} \ No newline at end of file