alioth/before/cha/09=real-time-communication/Server/ws.js
2025-05-30 09:18:01 +08:00

86 lines
2.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// | ------------------------------------------------------------
// | @版本: version 0.1
// | @创建人: 【Nie-x7129】
// | @E-mail: x71291@outlook.com
// | @文件描述: ws.js | 通过WebSocket建立服务
// | @创建时间: 2023-08-30 15:08
// | @更新时间: 2023-08-30 15:08
// | @修改记录:
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
// | =
// | ------------------------------------------------------------
// 引入WebSocketServer
import WebSocket, { WebSocketServer } from 'ws';
// 文件操作
import { createServer } from 'https';
import { readFileSync } from 'fs';
// = 函数名: httpWebSocket
// = 描述: 使用http模式建立WebSocket服务
// = 参数: None
// = 返回值: undefined
// = 创建人: Nier
// = 创建时间: 2023-08-30 15:12:57 -
async function httpWebSocket() {
// @ option - Object - 描述webSocket配置项
const option = {
// 创建服务器 必须提供 port、server、noServer其中任意一个 否则报错
port:10001, // 类型:Number 服务器端口号
host:'10.10.10.10', // 类型:String 服务器ip主机名
backlog:50, // 类型:Number 最大等待连接队列的长度
// server // 类型:http.Server|https.Server 预先创建的http或https的服务器
// path:'message', // 只接受与此路径匹配的连接。
// noServer:false, // 类型:Boolean 不启用服务器模式
//clientTracking // 指定是否跟踪客户端
maxPayload:4096, // 允许的最大消息大小(以字节为单位),默认为 100 MiB104857600 字节)。
}
const wss = new WebSocketServer(option,() => {
console.log(`HTTP WebSocket 已启动: ws://${option.host}:${option.port}`)
});
wss.on('connection', function connection(ws) {
console.log('Conn')
ws.on('error', console.error);
ws.on('message', function message(data, isBinary) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data, { binary: isBinary });
}
});
});
ws.onclose = event => {
console.log('Close')
}
});
}
// = 函数名: httpsWebSocket
// = 描述: 使用https模式建立WebSocket服务
// = 参数: None
// = 返回值: undefined
// = 创建人: Nier
// = 创建时间: 2023-08-30 15:13:30 -
function httpsWebSocket() {
const server = createServer({
cert: readFileSync('/path/to/cert.pem'),
key: readFileSync('/path/to/key.pem')
});
const wss = new WebSocketServer({ server, port: 10002 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});
}
export {
httpWebSocket,
httpsWebSocket
}