Skip to content

Bun のサーバーサイド WebSocket API はネイティブの pub-sub API を提供します。ソケットは socket.subscribe(<name>) を使用して名前付きチャンネルのセットに登録できます。メッセージは socket.publish(<name>, <message>) を使用してチャンネルに公開できます。

このコードスニペットはシンプルなシングルチャンネルチャットサーバーを実装しています。

ts
const server = Bun.serve({
  fetch(req, server) {
    const cookies = req.headers.get("cookie");
    const username = getUsernameFromCookies(cookies);
    const success = server.upgrade(req, { data: { username } });
    if (success) return undefined;

    return new Response("Hello world");
  },
  websocket: {
    // TypeScript: ws.data の型をこのように指定します
    data: {} as { username: string },

    open(ws) {
      const msg = `${ws.data.username} がチャットに参加しました`;
      ws.subscribe("the-group-chat");
      server.publish("the-group-chat", msg);
    },
    message(ws, message) {
      // サーバーは受信メッセージを全員に再放送します
      server.publish("the-group-chat", `${ws.data.username}: ${message}`);
    },
    close(ws) {
      const msg = `${ws.data.username} がチャットから退出しました`;
      server.publish("the-group-chat", msg);
      ws.unsubscribe("the-group-chat");
    },
  },
});

console.log(`${server.hostname}:${server.port} でリッスンしています`);

Bun by www.bunjs.com.cn 編集