본문 바로가기
C.W.K.
Stream
Lesson 01 of 08 · published

WebSocket 연결 만들기

~12 min · browser, constructor

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

한 줄이면 연결이 시작돼

브라우저의 WebSocket 생성자는 놀랄 만큼 단순해. new WebSocket(url) 을 호출하면 곧바로 프로토콜 전환 핸드셰이크를 시작하고, 생성자가 동기적으로 객체를 돌려준 뒤에도 백그라운드에서 연결 협상을 이어 가. open 이벤트가 오기 전에는 아무것도 보낼 수 없지만, 객체는 이미 있으니 이벤트 수신기는 미리 달 수 있어.

하위 프로토콜

두 번째 인자로 하위 프로토콜 이름 하나 또는 이름 배열을 줄 수 있어. 서버는 핸드셰이크 중 하나를 선택하거나 모두 거절하지. graphql-ws, graphql-transport-ws, mqtt 가 흔한 예야. openws.protocol 을 보면 서버가 선택한 값을 알 수 있어.

URL 을 통한 인증

브라우저 기본 WebSocket 생성자에는 fetch 처럼 사용자 지정 HTTP 헤더를 넣는 선택지가 없어. 그래서 인증 토큰을 URL 쿼리 매개변수로 넘기는 경우가 많아. wss:// 를 쓰면 전송 중 URL 은 암호화되지만 쿼리 문자열은 서버 접근 로그에 남기 쉬워. 오래 유효한 비밀값 대신 수명이 짧은 서명 토큰을 사용해야 해.

Code

생성자 사용 방식·javascript
// Plain
const ws = new WebSocket('ws://localhost:8000/ws');

// TLS for production
const wss = new WebSocket('wss://api.example.com/ws');

// With auth token in the query string
const auth = new WebSocket(
  'wss://api.example.com/ws?token=' + encodeURIComponent(jwt)
);

// Subprotocol negotiation
const sub = new WebSocket(
  'wss://api.example.com/ws',
  ['graphql-transport-ws', 'graphql-ws']
);
sub.addEventListener('open', () => {
  console.log('server picked:', sub.protocol);
});
readyState 상태 전이·javascript
const ws = new WebSocket('ws://localhost:8000/ws');

console.log(ws.readyState); // 0 (CONNECTING) — synchronous return

ws.addEventListener('open', () => {
  console.log(ws.readyState);  // 1 (OPEN)
  console.log(ws.protocol);    // selected subprotocol or ''
  console.log(ws.url);         // 'ws://localhost:8000/ws'
  console.log(ws.extensions);  // negotiated extensions or ''
});

External links

Exercise

wss://echo.websocket.org/ 또는 다른 에코 서비스를 개발자 도구에서 열어. WebSocket 을 만든 직후, open 처리기 안, open 후 100ms 가 지난 시점에 각각 readyState 를 기록해 동기 반환과 비동기 연결의 상태 전이를 확인해. 그런 다음 실제 서버에서 존재하지 않는 경로로 연결해 readyState 가 1 을 거치지 않고 0 에서 3 으로 바뀌는지 봐.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.