This commit is contained in:
2025-10-14 15:16:41 +08:00
parent e8794912b6
commit 27b63e0a2b
6 changed files with 89 additions and 40 deletions

View File

@@ -43,10 +43,11 @@ export class WsServerBase {
this.listening = true;
this.wss.on('connection', (ws) => {
ws.on('message', async (message: string) => {
ws.on('message', async (message: string | Buffer) => {
const data = parseIfJson(message);
if (typeof data === 'string') {
ws.emit('string', data);
const cleanMessage = data.trim().replace(/^["']|["']$/g, '');
ws.emit('string', cleanMessage);
return;
}
const { type, data: typeData, ...rest } = data;
@@ -83,7 +84,7 @@ export class WsServerBase {
if (message === 'close') {
ws.close();
}
if (message === 'ping') {
if (message == 'ping') {
ws.send('pong');
}
});

25
src/test/ws.ts Normal file
View File

@@ -0,0 +1,25 @@
import { App } from "../app.ts";
const app = new App({
io: true
});
app
.route('demo', '03')
.define(async (ctx) => {
ctx.body = '03';
return ctx;
})
.addTo(app);
app
.route('test', 'test')
.define(async (ctx) => {
ctx.body = 'test';
return ctx;
})
.addTo(app);
console.log(`http://localhost:4002/api/router?path=demo&key=03`);
app.listen(4002, () => {
console.log("Server started on http://localhost:4002");
});

View File

@@ -1,7 +1,8 @@
export const parseIfJson = (input: string): { [key: string]: any } | string => {
export const parseIfJson = (input: string|Buffer): { [key: string]: any } | string => {
const str = typeof input === 'string' ? input : input.toString();
try {
// 尝试解析 JSON
const parsed = JSON.parse(input);
const parsed = JSON.parse(str);
// 检查解析结果是否为对象(数组或普通对象)
if (typeof parsed === 'object' && parsed !== null) {
return parsed;
@@ -9,5 +10,5 @@ export const parseIfJson = (input: string): { [key: string]: any } | string => {
} catch (e) {
// 如果解析失败,直接返回原始字符串
}
return input;
return str;
};