feat: Implement LiveCode module with WebSocket and SSE support
- Added config management using `useConfig` for environment variables. - Created `LiveCode` class to manage WebSocket connections and routing. - Implemented `SSEManager` for Server-Sent Events handling. - Developed `WSSManager` for managing WebSocket connections with heartbeat functionality. - Introduced `ReconnectingWebSocket` class for robust WebSocket client with automatic reconnection. - Added test files for live application demonstrating WebSocket and TCP server integration.
This commit is contained in:
75
assistant/src/test/live-app.ts
Normal file
75
assistant/src/test/live-app.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
|
||||
import { App } from '@kevisual/router'
|
||||
import { WebSocket } from 'ws'
|
||||
import { ReconnectingWebSocket, handleCallApp } from '@kevisual/router/ws'
|
||||
import net from 'net';
|
||||
|
||||
const app = new App();
|
||||
|
||||
app.route({
|
||||
path: 'livecode-status',
|
||||
description: 'LiveCode 状态路由',
|
||||
metadata: {
|
||||
tags: ['livecode', 'status'],
|
||||
},
|
||||
}).define(async (ctx) => {
|
||||
ctx.body = {
|
||||
status: 'LiveCode 模块运行正常',
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
}).addTo(app)
|
||||
|
||||
app.createRouteList();
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
// 创建支持断开重连的 WebSocket 客户端
|
||||
const ws = new ReconnectingWebSocket('ws://localhost:51516/livecode/ws?id=test-live-app', {
|
||||
maxRetries: Infinity, // 无限重试
|
||||
retryDelay: 1000, // 初始重试延迟 1 秒
|
||||
maxDelay: 30000, // 最大延迟 30 秒
|
||||
backoffMultiplier: 2, // 指数退避倍数
|
||||
});
|
||||
ws.onMessage(async (message) => {
|
||||
console.log('收到消息:', message);
|
||||
if (message.type === 'router' && message.id) {
|
||||
console.log('收到路由响应:', message);
|
||||
const data = message?.data;
|
||||
if (!data) {
|
||||
ws.send({
|
||||
type: 'router',
|
||||
id: message.id,
|
||||
data: { code: 500, message: 'No data received' }
|
||||
});
|
||||
return;
|
||||
}
|
||||
const res = await app.run(message.data);
|
||||
console.log('路由处理结果:', res);
|
||||
ws.send({
|
||||
type: 'router',
|
||||
id: message.id,
|
||||
data: res
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
ws.onOpen(() => {
|
||||
console.log('连接已建立,可以开始通信');
|
||||
});
|
||||
|
||||
ws.onError((error) => {
|
||||
console.error('连接错误:', error.message);
|
||||
});
|
||||
|
||||
ws.onClose((code, reason) => {
|
||||
console.log(`连接关闭: ${code} - ${reason.toString()}`);
|
||||
});
|
||||
|
||||
// 启动连接
|
||||
ws.connect();
|
||||
|
||||
|
||||
net.createServer((socket) => {
|
||||
console.log('TCP 客户端已连接');
|
||||
}).listen(61616, () => {
|
||||
console.log('TCP 服务器正在监听端口 61616');
|
||||
});
|
||||
Reference in New Issue
Block a user