Skip to content
在 AI 工具中打开 Anthropic

WebSocket

天堂条约通过 subscribe 方法支持 WebSocket。

typescript
import { Elysia, t } from "elysia";
import { treaty } from "@elysia/eden";

const app = new Elysia()
  .ws("/chat", {
    body: t.String(),
    response: t.String(),
    message(ws, message) {
      ws.send(message);
    },
  })
  .listen(3000);

const api = treaty<typeof app>("localhost:3000");

const chat = api.chat.subscribe();

chat.subscribe((message) => {
  console.log("收到", message);
});

chat.on("open", () => {
  chat.send("来自客户端的问候");
});

.subscribe 接受与 gethead 相同的参数。

响应

Eden.subscribe 返回 EdenWS,它扩展了 WebSocket,因此支持完全相同的语法。

如果需要更多控制,可以访问 EdenWebSocket.raw 来操作原生的 WebSocket API。