1
0
Code Issues Pull Requests Projects Releases Wiki Activity GitHub Gitee

server & client 新增 & 调整

This commit is contained in:
程序员小墨 2023-07-29 22:28:21 +08:00
parent 7683831186
commit cc3a74468a
7 changed files with 246 additions and 1 deletions

View File

@ -1,3 +1,7 @@
/**
* HTTP Server (node demo)
* CommonJS
*/
const http = require('http');
const url = require('url');

View File

@ -1,3 +1,7 @@
/**
* TCP Server (node demo)
* CommonJS
*/
//引入net模块
const net = require('net');
//实例化一个服务器对象

View File

@ -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)
}
})
}
}

View File

@ -1,3 +1,7 @@
<!--
WebSocket Client (browser demo)
ECMAScript
-->
<!DOCTYPE html>
<html lang="en">

View File

@ -1,5 +1,6 @@
/**
* node websocket server
* WebSocket Client - with retry (node demo)
* CommonJS
*/
// 引入websocket依赖
const WebSocket = require('websocket').client;

View File

@ -1,3 +1,7 @@
/**
* WebSocket Client (node demo)
* CommonJS
*/
// 引入websocket依赖
const WebSocket = require('websocket').client;

View File

@ -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,
}