| 8 | |
| 9 | // websocket handler |
| 10 | export function setupWebsocketHandler(app: Express): [http.Server, WebSocketServer] { |
| 11 | const server = http.createServer(app); |
| 12 | const wss = new WebSocketServer({ noServer: true }); |
| 13 | |
| 14 | // task event channel |
| 15 | const clientMap: Map<string, WebSocket> = new Map(); |
| 16 | |
| 17 | // comfyui event channel |
| 18 | const comfyUIClients: WebSocket[] = []; |
| 19 | const comfyUIMessages:string[] = []; |
| 20 | |
| 21 | server.on("upgrade", (req: http.IncomingMessage, socket, head) => { |
| 22 | const ret = url.parse(req.url as string, true); |
| 23 | if (ret.pathname === '/ws') { |
| 24 | const clientId = (ret.query as any).clientId |
| 25 | if (clientId) { |
| 26 | wss.handleUpgrade(req, socket, head, ws => { |
| 27 | logger.info("set ws for, ", clientId); |
| 28 | clientMap.set(clientId, ws); |
| 29 | ws.on('message', function incoming(message: string) { |
| 30 | logger.info("recieved Message", clientId, message); |
| 31 | }); |
| 32 | ws.on('close', () => { |
| 33 | clientMap.delete(clientId); |
| 34 | }); |
| 35 | }); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | if (ret.pathname === "/ws/comfyui") { |
| 40 | wss.handleUpgrade(req, socket, head, ws => { |
| 41 | logger.info("connected comfyui ws"); |
| 42 | comfyUIClients.push(ws); |
| 43 | comfyUIMessages.forEach(message => { |
| 44 | ws.send(message); |
| 45 | }); |
| 46 | ws.on('message', function incoming(message: Buffer) { |
| 47 | const msg = message.toString(); |
| 48 | try { |
| 49 | const event = JSON.parse(msg); |
| 50 | comfyuiService.inputEvent.emit({ |
| 51 | command: event.command, |
| 52 | }); |
| 53 | } catch(err: any) { |
| 54 | logger.error("parse message error" + err.message); |
| 55 | console.log(err); |
| 56 | } |
| 57 | }); |
| 58 | ws.on('close', () => { |
| 59 | comfyUIClients.splice(comfyUIClients.indexOf(ws), 1); |
| 60 | }); |
| 61 | }); |
| 62 | } |
| 63 | }); |
| 64 | |
| 65 | taskQueue.progressEvent.on((event: TaskEvent) => { |
| 66 | const ws = clientMap.get(event.task.taskId); |
| 67 | if (ws) { |