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