WebSocket API 包含原生发布-订阅功能。使用 socket.subscribe(<名称>) 将套接字订阅到一组命名频道;使用 socket.publish(<名称>, <消息>) 向频道发布消息。
此代码片段实现了一个单频道聊天服务器。
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}`);