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}`);