@oox/ws 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +0 -0
- package/adapter.js +46 -0
- package/index.js +23 -0
- package/package.json +33 -0
- package/server.js +194 -0
- package/socket.js +163 -0
- package/types/adapter.d.ts +7 -0
- package/types/index.d.ts +4 -0
- package/types/server.d.ts +45 -0
- package/types/socket.d.ts +54 -0
- package/types/utils.d.ts +14 -0
- package/utils.js +44 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2020 lipingruan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
File without changes
|
package/adapter.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import * as oox from 'oox';
|
|
3
|
+
import { SampleKeepAliveConnectionAdapter } from 'oox/samples';
|
|
4
|
+
import { Socket } from './socket.js';
|
|
5
|
+
import { genWebSocketURL } from './utils.js';
|
|
6
|
+
export default class WebSocketAdapter extends SampleKeepAliveConnectionAdapter {
|
|
7
|
+
name = 'ws';
|
|
8
|
+
newConnection(identify) {
|
|
9
|
+
const { id, name } = oox.config;
|
|
10
|
+
const headers = {
|
|
11
|
+
'x-caller': name,
|
|
12
|
+
'x-caller-id': id,
|
|
13
|
+
};
|
|
14
|
+
let mURL;
|
|
15
|
+
const connectionData = {
|
|
16
|
+
name: 'anonymous',
|
|
17
|
+
id: randomUUID(),
|
|
18
|
+
adapter: this.name,
|
|
19
|
+
ip: '',
|
|
20
|
+
token: ''
|
|
21
|
+
};
|
|
22
|
+
if ('string' === typeof identify) {
|
|
23
|
+
mURL = genWebSocketURL(identify);
|
|
24
|
+
}
|
|
25
|
+
else if (identify instanceof URL) {
|
|
26
|
+
mURL = identify;
|
|
27
|
+
}
|
|
28
|
+
else if (identify.url) {
|
|
29
|
+
// KeepAliveConnectionData
|
|
30
|
+
Object.assign(connectionData, identify);
|
|
31
|
+
mURL = new URL(identify.url);
|
|
32
|
+
if (identify.token) {
|
|
33
|
+
headers['x-token'] = identify.token;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
throw new Error('identify must be string, URL, or KeepAliveConnectionData');
|
|
38
|
+
}
|
|
39
|
+
const socket = new Socket(mURL, {
|
|
40
|
+
headers,
|
|
41
|
+
autoPong: true,
|
|
42
|
+
});
|
|
43
|
+
const connection = new oox.KeepAliveConnection(this, socket, connectionData);
|
|
44
|
+
return connection;
|
|
45
|
+
}
|
|
46
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import * as PATH from 'node:path';
|
|
2
|
+
import * as oox from 'oox';
|
|
3
|
+
import WebSocketServer from './server.js';
|
|
4
|
+
export default class WebSocketModule extends WebSocketServer {
|
|
5
|
+
async serve() {
|
|
6
|
+
await this.stop();
|
|
7
|
+
const _http = oox.modules.builtins.http;
|
|
8
|
+
const httpConfig = _http.getConfig(), config = this.getConfig();
|
|
9
|
+
let isShareServer = false;
|
|
10
|
+
// 都没设置端口
|
|
11
|
+
isShareServer = !httpConfig.port && !config.port;
|
|
12
|
+
// 都设置相同端口
|
|
13
|
+
isShareServer ||= httpConfig.port === config.port;
|
|
14
|
+
// http 模块未被禁用
|
|
15
|
+
isShareServer &&= httpConfig.enabled;
|
|
16
|
+
if (isShareServer) {
|
|
17
|
+
config.path = PATH.posix.join(httpConfig.path, config.path);
|
|
18
|
+
this.server = _http.server;
|
|
19
|
+
this.config.ssl = _http.config.ssl;
|
|
20
|
+
}
|
|
21
|
+
await super.serve();
|
|
22
|
+
}
|
|
23
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@oox/ws",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "OOX WebSocket Module",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public",
|
|
7
|
+
"registry": "https://registry.npmjs.org/"
|
|
8
|
+
},
|
|
9
|
+
"main": "index.js",
|
|
10
|
+
"types": "./types/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": "./index.js",
|
|
14
|
+
"require": "./index.js",
|
|
15
|
+
"types": "./types/index.d.ts"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"oox",
|
|
20
|
+
"ws",
|
|
21
|
+
"module",
|
|
22
|
+
"websocket"
|
|
23
|
+
],
|
|
24
|
+
"author": "lipingruan",
|
|
25
|
+
"email": "hello@ruanmail.com",
|
|
26
|
+
"homepage": "https://gitee.com/lipingruan/oox/tree/main/packages/oox-ws",
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"type": "module",
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@msgpack/msgpack": "^3.1.3",
|
|
31
|
+
"ws": "^8.20.0"
|
|
32
|
+
}
|
|
33
|
+
}
|
package/server.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import * as http from 'node:http';
|
|
2
|
+
import * as https from 'node:https';
|
|
3
|
+
import { WebSocketServer as Server } from 'ws';
|
|
4
|
+
import * as oox from 'oox';
|
|
5
|
+
import { Module } from 'oox';
|
|
6
|
+
import { Socket } from './socket.js';
|
|
7
|
+
import WebSocketAdapter from './adapter.js';
|
|
8
|
+
import { OOXEvent } from './utils.js';
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
10
|
+
export class WebSocketConfig {
|
|
11
|
+
enabled = true;
|
|
12
|
+
// listen port
|
|
13
|
+
port = 0;
|
|
14
|
+
// service path
|
|
15
|
+
path = '/ws';
|
|
16
|
+
// browser cross origin
|
|
17
|
+
origin = '';
|
|
18
|
+
// https options
|
|
19
|
+
ssl = {
|
|
20
|
+
// enable https
|
|
21
|
+
enabled: false,
|
|
22
|
+
// ssl certificate path
|
|
23
|
+
cert: '',
|
|
24
|
+
// ssl private key path
|
|
25
|
+
key: '',
|
|
26
|
+
// ssl ca path
|
|
27
|
+
ca: ''
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export default class WebSocketServer extends Module {
|
|
31
|
+
name = 'ws';
|
|
32
|
+
config = new WebSocketConfig;
|
|
33
|
+
/**
|
|
34
|
+
* means this.server created by myself<SocketIOServer>
|
|
35
|
+
*/
|
|
36
|
+
#isSelfServer = false;
|
|
37
|
+
server = null;
|
|
38
|
+
socketServer = null;
|
|
39
|
+
adapter = new WebSocketAdapter();
|
|
40
|
+
constructor() {
|
|
41
|
+
super();
|
|
42
|
+
oox.keepAliveConnectionAdapters.set(this.name, this.adapter);
|
|
43
|
+
}
|
|
44
|
+
getURL() {
|
|
45
|
+
const { host } = oox.config;
|
|
46
|
+
const { port, path } = this.config;
|
|
47
|
+
const protocol = this.config.ssl.enabled ? 'wss:' : 'ws:';
|
|
48
|
+
return new URL(`${protocol}//${host}:${port}${path}`);
|
|
49
|
+
}
|
|
50
|
+
setConfig(config) {
|
|
51
|
+
Object.assign(this.config, config);
|
|
52
|
+
if (!config.hasOwnProperty('port')) {
|
|
53
|
+
this.config.port = oox.config.port;
|
|
54
|
+
}
|
|
55
|
+
if (!config.hasOwnProperty('origin')) {
|
|
56
|
+
this.config.origin = oox.config.origin;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
getConfig() {
|
|
60
|
+
return this.config;
|
|
61
|
+
}
|
|
62
|
+
// 对外提供服务的URL
|
|
63
|
+
get serviceURL() {
|
|
64
|
+
return this.getURL();
|
|
65
|
+
}
|
|
66
|
+
async serve() {
|
|
67
|
+
await this.stop();
|
|
68
|
+
const { port, ssl } = this.config;
|
|
69
|
+
const isSelfServer = this.#isSelfServer = this.server ? true : false;
|
|
70
|
+
let server = null;
|
|
71
|
+
if (isSelfServer) {
|
|
72
|
+
if (!this.server)
|
|
73
|
+
throw new Error('HTTP Server is not created');
|
|
74
|
+
server = this.server;
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
if (ssl.enabled) {
|
|
78
|
+
const fs = await import('node:fs');
|
|
79
|
+
const options = {
|
|
80
|
+
key: ssl.key ? fs.readFileSync(ssl.key) : undefined,
|
|
81
|
+
cert: ssl.cert ? fs.readFileSync(ssl.cert) : undefined,
|
|
82
|
+
ca: ssl.ca ? fs.readFileSync(ssl.ca) : undefined
|
|
83
|
+
};
|
|
84
|
+
if (!options.key || !options.cert) {
|
|
85
|
+
throw new Error('HTTPS enabled but missing key or cert');
|
|
86
|
+
}
|
|
87
|
+
server = https.createServer(options, (_request, response) => response.end('No HTTP Gateway'));
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
server = http.createServer((_request, response) => response.end('No HTTP Gateway'));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
this.server = server;
|
|
94
|
+
if (!server.listening)
|
|
95
|
+
server.listen(port);
|
|
96
|
+
const address = server.address();
|
|
97
|
+
if (!address || 'object' !== typeof address)
|
|
98
|
+
throw new Error('Cannot read ws server port');
|
|
99
|
+
this.config.port = address.port;
|
|
100
|
+
this.createWebSocketServer();
|
|
101
|
+
console.log(`WebSocketServer is running on port ${this.config.port}`);
|
|
102
|
+
}
|
|
103
|
+
async stop() {
|
|
104
|
+
const { server, socketServer } = this;
|
|
105
|
+
if (socketServer)
|
|
106
|
+
await new Promise((resolve, reject) => socketServer.close(error => error ? reject(error) : resolve()));
|
|
107
|
+
if (this.#isSelfServer)
|
|
108
|
+
await new Promise((resolve, reject) => server?.close(error => error ? reject(error) : resolve()));
|
|
109
|
+
}
|
|
110
|
+
genWebSocketServerOptions() {
|
|
111
|
+
const options = {
|
|
112
|
+
/**
|
|
113
|
+
* name of the path to capture
|
|
114
|
+
* @default "/ws"
|
|
115
|
+
*/
|
|
116
|
+
path: this.config.path,
|
|
117
|
+
autoPong: true,
|
|
118
|
+
skipUTF8Validation: true,
|
|
119
|
+
WebSocket: Socket,
|
|
120
|
+
};
|
|
121
|
+
return options;
|
|
122
|
+
}
|
|
123
|
+
createWebSocketServer() {
|
|
124
|
+
const { server } = this;
|
|
125
|
+
if (!server)
|
|
126
|
+
throw new Error('HTTP Server is not created');
|
|
127
|
+
const socketServer = this.socketServer = new Server({
|
|
128
|
+
server,
|
|
129
|
+
...this.genWebSocketServerOptions(),
|
|
130
|
+
});
|
|
131
|
+
socketServer.on('connection', async (socket, req) => {
|
|
132
|
+
try {
|
|
133
|
+
this.serverOnSocketConnection(socket, req);
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
console.error(error);
|
|
137
|
+
socket.send(error.message);
|
|
138
|
+
socket.disconnect();
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* 服务端Socket连接事件
|
|
144
|
+
*/
|
|
145
|
+
serverOnSocketConnection(socket, req) {
|
|
146
|
+
const headers = req.headers;
|
|
147
|
+
const url = new URL(req.url || '', req.headers['origin'] || 'ws://localhost');
|
|
148
|
+
const query = url.searchParams;
|
|
149
|
+
const callerId = String(headers['x-caller-id'] || query.get('x-caller-id') || randomUUID());
|
|
150
|
+
// client ip or caller service ip
|
|
151
|
+
const ip = String(headers['x-real-ip'] || req.socket.remoteAddress || '');
|
|
152
|
+
// service name
|
|
153
|
+
const caller = String(headers['x-caller'] || query.get('x-caller') || 'anonymous');
|
|
154
|
+
const token = String(headers['x-token'] || query.get('x-token') || '');
|
|
155
|
+
// check token
|
|
156
|
+
const { allow, reason } = oox.checkAllow(ip, caller, token);
|
|
157
|
+
if (!allow) {
|
|
158
|
+
socket.send(reason);
|
|
159
|
+
socket.disconnect();
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const connection = new oox.KeepAliveConnection(this.adapter, socket, {
|
|
163
|
+
ip,
|
|
164
|
+
name: caller,
|
|
165
|
+
id: callerId,
|
|
166
|
+
token,
|
|
167
|
+
});
|
|
168
|
+
oox.addKeepAliveConnection(connection);
|
|
169
|
+
this.bindServerConnectionEvents(connection);
|
|
170
|
+
socket.emit(OOXEvent.READY, {
|
|
171
|
+
id: oox.config.id,
|
|
172
|
+
name: oox.config.name
|
|
173
|
+
});
|
|
174
|
+
connection.enabled = true;
|
|
175
|
+
this.adapter.bindCall(connection);
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* 绑定服务器连接事件
|
|
179
|
+
* @param connection
|
|
180
|
+
*/
|
|
181
|
+
bindServerConnectionEvents(connection) {
|
|
182
|
+
const socket = connection.nativeConnection;
|
|
183
|
+
socket.on(OOXEvent.REGISTRY_SYNC_CONNECTIONS, async (fn) => {
|
|
184
|
+
if ('function' !== typeof fn)
|
|
185
|
+
return;
|
|
186
|
+
oox.registry.onSyncConnections(connection, {}, fn);
|
|
187
|
+
});
|
|
188
|
+
socket.on('close', (reason) => {
|
|
189
|
+
oox.removeKeepAliveConnection(connection);
|
|
190
|
+
socket.removeAllListeners();
|
|
191
|
+
connection.emit('disconnect');
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
}
|
package/socket.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { WebSocket } from 'ws';
|
|
2
|
+
import { encode, decode } from '@msgpack/msgpack';
|
|
3
|
+
export const WebsocketEvents = [
|
|
4
|
+
'close',
|
|
5
|
+
'error',
|
|
6
|
+
'message',
|
|
7
|
+
'open',
|
|
8
|
+
'upgrade',
|
|
9
|
+
'ping',
|
|
10
|
+
'pong',
|
|
11
|
+
'redirect',
|
|
12
|
+
'unexpected-response'
|
|
13
|
+
];
|
|
14
|
+
// 消息Pack编码选项
|
|
15
|
+
export const MessagePackEncodeOptions = {
|
|
16
|
+
ignoreUndefined: true
|
|
17
|
+
};
|
|
18
|
+
// RPC事件类型
|
|
19
|
+
export var RPCType;
|
|
20
|
+
(function (RPCType) {
|
|
21
|
+
RPCType[RPCType["Request"] = 1] = "Request";
|
|
22
|
+
RPCType[RPCType["Response"] = 2] = "Response";
|
|
23
|
+
})(RPCType || (RPCType = {}));
|
|
24
|
+
// 最大请求ID
|
|
25
|
+
export const MAX_REQUEST_ID = 0xFFFFFFFF;
|
|
26
|
+
// 非WebSocket事件前缀
|
|
27
|
+
export const ExtEventPrefix = 'ext:';
|
|
28
|
+
export class Socket extends WebSocket {
|
|
29
|
+
callbacks;
|
|
30
|
+
requestId;
|
|
31
|
+
connected = false;
|
|
32
|
+
constructor(...args) {
|
|
33
|
+
super(...args);
|
|
34
|
+
this.callbacks = new Map();
|
|
35
|
+
this.requestId = 0;
|
|
36
|
+
super.on('open', () => {
|
|
37
|
+
this.connected = true;
|
|
38
|
+
});
|
|
39
|
+
super.on('close', () => {
|
|
40
|
+
this.connected = false;
|
|
41
|
+
this.callbacks.clear();
|
|
42
|
+
});
|
|
43
|
+
super.on('error', (error) => {
|
|
44
|
+
this.connected = false;
|
|
45
|
+
this.callbacks.clear();
|
|
46
|
+
});
|
|
47
|
+
// 监听消息
|
|
48
|
+
super.on('message', (message, isBinary) => {
|
|
49
|
+
this.handleMessage(message, isBinary);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
isNativeEvent(event) {
|
|
53
|
+
return WebsocketEvents.includes(event);
|
|
54
|
+
}
|
|
55
|
+
off(event, listener) {
|
|
56
|
+
if (!event) {
|
|
57
|
+
return super.removeAllListeners();
|
|
58
|
+
}
|
|
59
|
+
else if (!listener) {
|
|
60
|
+
return super.removeAllListeners(event);
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
return super.off(event, listener);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
emit(event, ...args) {
|
|
67
|
+
if (this.isNativeEvent(event)) {
|
|
68
|
+
return super.emit(event, ...args);
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
this.rpc(event, ...args);
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* 生成自增请求ID
|
|
77
|
+
*/
|
|
78
|
+
generateRequestId() {
|
|
79
|
+
// 处理上限翻转
|
|
80
|
+
if (this.requestId >= MAX_REQUEST_ID) {
|
|
81
|
+
this.requestId = 0;
|
|
82
|
+
}
|
|
83
|
+
return ++this.requestId;
|
|
84
|
+
}
|
|
85
|
+
disconnect() {
|
|
86
|
+
this.connected = false;
|
|
87
|
+
this.close();
|
|
88
|
+
}
|
|
89
|
+
connect() { }
|
|
90
|
+
/**
|
|
91
|
+
* 发送RPC消息
|
|
92
|
+
*/
|
|
93
|
+
sendRPCMessage(message) {
|
|
94
|
+
const buffer = encode(message, MessagePackEncodeOptions);
|
|
95
|
+
this.send(buffer);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* 处理消息
|
|
99
|
+
*/
|
|
100
|
+
handleMessage(message, isBinary) {
|
|
101
|
+
if (isBinary) {
|
|
102
|
+
this.handleRPC(message);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* 处理RPC消息
|
|
107
|
+
*/
|
|
108
|
+
handleRPC(message) {
|
|
109
|
+
try {
|
|
110
|
+
const data = decode(message);
|
|
111
|
+
const { type, event, args, id } = data;
|
|
112
|
+
if (type === RPCType.Request) {
|
|
113
|
+
if (typeof event !== 'string')
|
|
114
|
+
return;
|
|
115
|
+
if (this.isNativeEvent(event))
|
|
116
|
+
return;
|
|
117
|
+
const nArgs = Array.isArray(args) ? args : [args];
|
|
118
|
+
// 触发事件,等待回调函数
|
|
119
|
+
super.emit(event, ...nArgs, (...returns) => {
|
|
120
|
+
if (id !== undefined) {
|
|
121
|
+
// 发送响应消息
|
|
122
|
+
this.sendRPCMessage({
|
|
123
|
+
type: RPCType.Response,
|
|
124
|
+
id,
|
|
125
|
+
args: returns
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
else if (type === RPCType.Response && id !== undefined) {
|
|
131
|
+
const callback = this.callbacks.get(id);
|
|
132
|
+
if (callback) {
|
|
133
|
+
this.callbacks.delete(id);
|
|
134
|
+
const nArgs = Array.isArray(args) ? args : [args];
|
|
135
|
+
callback(...nArgs);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
console.error('Error handling message:', error);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
rpc(event, ...args) {
|
|
144
|
+
let callback;
|
|
145
|
+
let id;
|
|
146
|
+
// 检查最后一个参数是否是回调函数
|
|
147
|
+
if (args.length > 0 && typeof args[args.length - 1] === 'function') {
|
|
148
|
+
callback = args.pop();
|
|
149
|
+
id = this.generateRequestId();
|
|
150
|
+
}
|
|
151
|
+
// 发送消息
|
|
152
|
+
this.sendRPCMessage({
|
|
153
|
+
type: RPCType.Request,
|
|
154
|
+
event,
|
|
155
|
+
args,
|
|
156
|
+
id
|
|
157
|
+
});
|
|
158
|
+
// 如果提供了回调函数,使用回调模式
|
|
159
|
+
if (callback && id !== undefined) {
|
|
160
|
+
this.callbacks.set(id, callback);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import * as oox from 'oox';
|
|
2
|
+
import { SampleKeepAliveConnectionAdapter } from 'oox/samples';
|
|
3
|
+
import { Socket } from './socket.js';
|
|
4
|
+
export default class WebSocketAdapter extends SampleKeepAliveConnectionAdapter<Socket> {
|
|
5
|
+
name: string;
|
|
6
|
+
newConnection(identify: string | URL | oox.KeepAliveConnectionData): oox.KeepAliveConnection<Socket>;
|
|
7
|
+
}
|
package/types/index.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import * as http from 'node:http';
|
|
2
|
+
import * as https from 'node:https';
|
|
3
|
+
import { WebSocketServer as Server, ServerOptions } from 'ws';
|
|
4
|
+
import * as oox from 'oox';
|
|
5
|
+
import { Module, ModuleConfig } from 'oox';
|
|
6
|
+
import { Socket } from './socket.js';
|
|
7
|
+
import WebSocketAdapter from './adapter.js';
|
|
8
|
+
export declare class WebSocketConfig implements ModuleConfig {
|
|
9
|
+
enabled: boolean;
|
|
10
|
+
port: number;
|
|
11
|
+
path: string;
|
|
12
|
+
origin: string | string[];
|
|
13
|
+
ssl: {
|
|
14
|
+
enabled: boolean;
|
|
15
|
+
cert: string;
|
|
16
|
+
key: string;
|
|
17
|
+
ca: string;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export default class WebSocketServer extends Module {
|
|
21
|
+
#private;
|
|
22
|
+
name: string;
|
|
23
|
+
config: WebSocketConfig;
|
|
24
|
+
server: http.Server | https.Server | null;
|
|
25
|
+
socketServer: Server | null;
|
|
26
|
+
adapter: WebSocketAdapter;
|
|
27
|
+
constructor();
|
|
28
|
+
getURL(): URL;
|
|
29
|
+
setConfig(config: WebSocketConfig): void;
|
|
30
|
+
getConfig(): WebSocketConfig;
|
|
31
|
+
get serviceURL(): URL;
|
|
32
|
+
serve(): Promise<void>;
|
|
33
|
+
stop(): Promise<void>;
|
|
34
|
+
genWebSocketServerOptions(): Partial<ServerOptions<typeof import("ws").default, typeof http.IncomingMessage>>;
|
|
35
|
+
createWebSocketServer(): void;
|
|
36
|
+
/**
|
|
37
|
+
* 服务端Socket连接事件
|
|
38
|
+
*/
|
|
39
|
+
serverOnSocketConnection(socket: Socket, req: http.IncomingMessage): void;
|
|
40
|
+
/**
|
|
41
|
+
* 绑定服务器连接事件
|
|
42
|
+
* @param connection
|
|
43
|
+
*/
|
|
44
|
+
bindServerConnectionEvents(connection: oox.KeepAliveConnection<Socket>): void;
|
|
45
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { ClientRequestArgs } from 'node:http';
|
|
2
|
+
import { WebSocket } from 'ws';
|
|
3
|
+
import { SampleKeepAliveNativeConnection } from 'oox/samples';
|
|
4
|
+
export declare const WebsocketEvents: readonly ["close", "error", "message", "open", "upgrade", "ping", "pong", "redirect", "unexpected-response"];
|
|
5
|
+
export type WebsocketEvent = (typeof WebsocketEvents)[number];
|
|
6
|
+
export declare const MessagePackEncodeOptions: {
|
|
7
|
+
ignoreUndefined: boolean;
|
|
8
|
+
};
|
|
9
|
+
export declare enum RPCType {
|
|
10
|
+
Request = 1,
|
|
11
|
+
Response = 2
|
|
12
|
+
}
|
|
13
|
+
export interface RPCMessage {
|
|
14
|
+
type: RPCType;
|
|
15
|
+
id?: number;
|
|
16
|
+
event?: string;
|
|
17
|
+
args: any[];
|
|
18
|
+
}
|
|
19
|
+
export declare const MAX_REQUEST_ID = 4294967295;
|
|
20
|
+
export declare const ExtEventPrefix = "ext:";
|
|
21
|
+
export type Callback = (...args: any[]) => void;
|
|
22
|
+
export declare class Socket extends WebSocket implements SampleKeepAliveNativeConnection {
|
|
23
|
+
private callbacks;
|
|
24
|
+
private requestId;
|
|
25
|
+
connected: boolean;
|
|
26
|
+
constructor(address: null);
|
|
27
|
+
constructor(address: string | URL, options?: WebSocket.ClientOptions | ClientRequestArgs);
|
|
28
|
+
constructor(address: string | URL, protocols?: string | string[], options?: WebSocket.ClientOptions | ClientRequestArgs);
|
|
29
|
+
isNativeEvent(event: string): boolean;
|
|
30
|
+
off(event: WebsocketEvent | string, listener?: (...args: any[]) => void): this;
|
|
31
|
+
emit(event: WebsocketEvent | string, ...args: any[]): boolean;
|
|
32
|
+
/**
|
|
33
|
+
* 生成自增请求ID
|
|
34
|
+
*/
|
|
35
|
+
private generateRequestId;
|
|
36
|
+
disconnect(): void;
|
|
37
|
+
connect(): void;
|
|
38
|
+
/**
|
|
39
|
+
* 发送RPC消息
|
|
40
|
+
*/
|
|
41
|
+
sendRPCMessage(message: RPCMessage): void;
|
|
42
|
+
/**
|
|
43
|
+
* 处理消息
|
|
44
|
+
*/
|
|
45
|
+
private handleMessage;
|
|
46
|
+
/**
|
|
47
|
+
* 处理RPC消息
|
|
48
|
+
*/
|
|
49
|
+
private handleRPC;
|
|
50
|
+
/**
|
|
51
|
+
* RPC调用
|
|
52
|
+
*/
|
|
53
|
+
rpc(event: string, ...args: any[]): void;
|
|
54
|
+
}
|
package/types/utils.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare const OOXEvent: {
|
|
2
|
+
CONNECT: string;
|
|
3
|
+
DISCONNECT: string;
|
|
4
|
+
ERROR: string;
|
|
5
|
+
CALL: string;
|
|
6
|
+
READY: string;
|
|
7
|
+
ENABLED: string;
|
|
8
|
+
DISABLED: string;
|
|
9
|
+
REGISTRY_SYNC_CONNECTIONS: string;
|
|
10
|
+
REGISTRY_SUBSCRIBE: string;
|
|
11
|
+
REGISTRY_NOTIFY: string;
|
|
12
|
+
};
|
|
13
|
+
export declare function isWebSocketURL(url: string | URL): boolean;
|
|
14
|
+
export declare function genWebSocketURL(url: string): URL;
|
package/utils.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export const OOXEvent = {
|
|
2
|
+
CONNECT: 'open',
|
|
3
|
+
DISCONNECT: 'close',
|
|
4
|
+
ERROR: 'socket:error',
|
|
5
|
+
CALL: 'call',
|
|
6
|
+
READY: 'oox:ready',
|
|
7
|
+
ENABLED: 'oox:enabled',
|
|
8
|
+
DISABLED: 'oox:disabled',
|
|
9
|
+
REGISTRY_SYNC_CONNECTIONS: 'oox:registry:sync_connections',
|
|
10
|
+
REGISTRY_SUBSCRIBE: 'oox:registry:subscribe',
|
|
11
|
+
REGISTRY_NOTIFY: 'oox:registry:notify',
|
|
12
|
+
};
|
|
13
|
+
export function isWebSocketURL(url) {
|
|
14
|
+
if ('string' === typeof url) {
|
|
15
|
+
return /^wss?:\/\/.+$/.test(url);
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
return url.protocol === 'ws:' || url.protocol === 'wss:';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export function genWebSocketURL(url) {
|
|
22
|
+
// :6000
|
|
23
|
+
if (url.startsWith(':'))
|
|
24
|
+
url = 'ws://localhost' + url;
|
|
25
|
+
// 127.0.0.1:6000
|
|
26
|
+
if (!/^\w+?:\/.+$/.test(url))
|
|
27
|
+
url = 'ws://' + url;
|
|
28
|
+
const urlObject = new URL(url);
|
|
29
|
+
// :8000 => :8000/ws
|
|
30
|
+
const notSetPath = !urlObject.pathname || (urlObject.pathname === '/'
|
|
31
|
+
&& !url.endsWith('/')
|
|
32
|
+
&& !urlObject.search
|
|
33
|
+
&& !urlObject.hash);
|
|
34
|
+
if (notSetPath) {
|
|
35
|
+
urlObject.pathname = '/ws';
|
|
36
|
+
}
|
|
37
|
+
if (urlObject.protocol !== 'wss:') {
|
|
38
|
+
if (urlObject.port === '443')
|
|
39
|
+
urlObject.protocol = 'wss:';
|
|
40
|
+
else
|
|
41
|
+
urlObject.protocol = 'ws:';
|
|
42
|
+
}
|
|
43
|
+
return urlObject;
|
|
44
|
+
}
|