-
Notifications
You must be signed in to change notification settings - Fork 228
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #701 from Stapxs/main
HTTP SSE 消息上报模式
- Loading branch information
Showing
4 changed files
with
67 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import { OB11EmitEventContent } from './index'; | ||
import { Request, Response } from 'express'; | ||
import { OB11Response } from '@/onebot/action/OneBotAction'; | ||
import { OB11PassiveHttpAdapter } from './passive-http'; | ||
|
||
export class OB11ActiveHttpSSEAdapter extends OB11PassiveHttpAdapter { | ||
private sseClients: Response[] = []; | ||
|
||
async handleRequest(req: Request, res: Response): Promise<any> { | ||
if (req.path === '/_events') { | ||
return this.createSseSupport(req, res); | ||
} else { | ||
super.httpApiRequest(req, res); | ||
} | ||
} | ||
|
||
private async createSseSupport(req: Request, res: Response) { | ||
res.setHeader('Content-Type', 'text/event-stream'); | ||
res.setHeader('Cache-Control', 'no-cache'); | ||
res.setHeader('Connection', 'keep-alive'); | ||
res.flushHeaders(); | ||
|
||
this.sseClients.push(res); | ||
req.on('close', () => { | ||
this.sseClients = this.sseClients.filter((client) => client !== res); | ||
}); | ||
} | ||
|
||
onEvent<T extends OB11EmitEventContent>(event: T) { | ||
this.sseClients.forEach((res) => { | ||
res.write(`data: ${JSON.stringify(event)}\n\n`); | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters