故事背景
- windows安装包总是会触发防火墙弹窗提示
- 720等卫士偶发封禁本地端口
localhost的websocket会有上百ms的延时
解释只监听localhost不会走网络协议,不会触发防火墙规则
名词解释
关键点
- SSE是个长连接
- 自定义协议通常用于简单的Request/Response形式,例如文件缓存等
- response支持body是一个stream
好处(aka. 为什么这么蛋疼)
上代码
// Electron main process
import { PassThrough } from 'node:stream';
import http from 'node:http';
import log from 'electron-log';
export async function handleSSE(request: GlobalRequest): Promise<GlobalResponse | undefined> {
const url = new URL(request.url);
if (url.host === 'xx.events') {
const resp = await listenSdk();
const stream = new PassThrough();
resp.pipe(stream);
return new Response(stream as unknown as ReadableStream, {
headers: resp.headers as Record<string, string>,
});
}
}
async function listenSdk(): Promise<http.IncomingMessage> {
return new Promise((resolve, reject) => {
const req = http.request({
socketPath: '/tmp/t-xxxxxx.sock', // win32: '//./pipe/xxxx/xx/uuid'.replaceAll('/', '\\');
path: '/listen',
method: 'GET',
}, (resp) => resolve(resp));
try {
req.on('error', (err) => {
reject(err);
req.destroy();
});
req.end();
} catch (error) {
reject(error);
}
})
}
// Electron renderer process
new EventSource('xxx-xxx://xx.events');
// SSE实现部分 -- 省略...