const server = Bun.serve({
fetch(req, server) {
const success = server.upgrade(req);
if (success) {
// Bun 在升级成功时自动返回 101 Switching Protocols
return undefined;
}
// 正常处理 HTTP 请求
return new Response("Hello world!");
},
websocket: {
// TypeScript:像这样指定 ws.data 的类型
data: {} as { authToken: string },
// 收到消息时调用
async message(ws, message) {
console.log(`收到:${message}`);
// 发送回复消息
ws.send(`你说了:${message}`);
},
},
});
console.log(`监听于 ${server.hostname}:${server.port}`);