Bun.serve 를 사용하여 간단한 WebSocket 서버를 시작합니다.
fetch 내부에서 들어오는 ws: 또는 wss: 요청을 WebSocket 연결로 업그레이드하려고 시도합니다.
ts
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} 에서 리스닝 중`);