update
This commit is contained in:
69
src/modules/ws-proxy/index.ts
Normal file
69
src/modules/ws-proxy/index.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { WebSocketServer } from 'ws';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { WsProxyManager } from './manager.ts';
|
||||
import { getLoginUser } from '@/modules/auth.ts';
|
||||
import { logger } from '../logger.ts';
|
||||
export const wsProxyManager = new WsProxyManager();
|
||||
|
||||
export const upgrade = async (request: any, socket: any, head: any) => {
|
||||
const req = request as any;
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
const id = url.searchParams.get('id');
|
||||
if (url.pathname === '/ws/proxy') {
|
||||
console.log('upgrade', request.url, id);
|
||||
wss.handleUpgrade(req, socket, head, (ws) => {
|
||||
// 这里手动触发 connection 事件
|
||||
// @ts-ignore
|
||||
wss.emit('connection', ws, req);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
export const wss = new WebSocketServer({
|
||||
noServer: true,
|
||||
path: '/ws/proxy',
|
||||
});
|
||||
|
||||
wss.on('connection', async (ws, req) => {
|
||||
console.log('connected', req.url);
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
const id = url?.searchParams?.get('id') || nanoid();
|
||||
const loginUser = await getLoginUser(req);
|
||||
if (!loginUser) {
|
||||
ws.send(JSON.stringify({ code: 401, message: 'No Login' }));
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
const user = loginUser.tokenUser?.username;
|
||||
wsProxyManager.register(id, { user, ws });
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'connected',
|
||||
user: user,
|
||||
id,
|
||||
}),
|
||||
);
|
||||
ws.on('message', async (event: Buffer) => {
|
||||
const eventData = event.toString();
|
||||
if (!eventData) {
|
||||
return;
|
||||
}
|
||||
const data = JSON.parse(eventData);
|
||||
logger.debug('message', data);
|
||||
});
|
||||
ws.on('close', () => {
|
||||
logger.debug('ws closed');
|
||||
wsProxyManager.unregister(id, user);
|
||||
});
|
||||
});
|
||||
|
||||
export class WssApp {
|
||||
wss: WebSocketServer;
|
||||
constructor() {
|
||||
this.wss = wss;
|
||||
}
|
||||
upgrade(request: any, socket: any, head: any) {
|
||||
return upgrade(request, socket, head);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user