본문 바로가기
C.W.K.
Stream
Lesson 03 of 07 · published

JavaScript Socket.IO 클라이언트

~11 min · library, socket-io-client, ack

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

한곳에 모인 클라이언트 API

브라우저와 Node 용 socket.io-clientio() 한 번으로 소켓을 만들어. 이 소켓은 자동 재연결, 이벤트 구독과 발행, 콜백 또는 Promise 방식의 ACK 를 지원해. 같은 SDK 가 Node, React Native, 현대적인 번들러에서 모두 작동해.

이벤트 이름은 자유로운 문자열이야

기본 WebSocket 과 달리 메시지 라우터를 직접 만들 필요가 없어. socket.on('chat:message', handler) 로 듣고 socket.emit('chat:message', payload) 로 보내면 돼. 라이브러리가 이벤트 이름을 내부 프레임 종류에 연결해 줘.

콜백 또는 Promise 로 받는 ACK

emit 의 마지막 인자로 콜백을 넘기면 라이브러리가 서버의 ACK 를 기다려. Promise 방식에는 emitWithAck 를 써. 서버 이벤트 처리기가 값이나 배열을 반환하면 그것이 ACK 데이터가 돼. 상관관계 ID 코드를 직접 만들지 않고도 요청과 응답을 구현할 수 있어.

Code

Socket.IO 클라이언트·javascript
import { io } from 'socket.io-client';

const socket = io('https://api.example.com', {
  auth: { token: 'jwt-here' },
  reconnection: true,
  reconnectionDelay: 1_000,
  reconnectionDelayMax: 30_000,
  randomizationFactor: 0.5,
});

socket.on('connect', () => {
  console.log('connected as', socket.id);
});

socket.on('disconnect', (reason) => {
  console.log('disconnected:', reason);
  // Common reasons: 'io server disconnect', 'io client disconnect',
  //                 'ping timeout', 'transport close', 'transport error'
});

socket.on('chat:message', (data) => {
  console.log(`${data.from}: ${data.text}`);
});

// Send + acknowledge with callback
socket.emit('chat:message', { room: 'general', text: 'hi' }, (ack) => {
  console.log('server ack:', ack);
});

// Send + acknowledge with promise (v4.6+)
const ack = await socket.emitWithAck('chat:message', {
  room: 'general', text: 'hi',
});

External links

Exercise

t6l2 서버에 Socket.IO 클라이언트를 연결해. chat:message 를 보내며 콜백 방식과 emitWithAck Promise 방식 ACK 를 모두 사용해. 처리기 안에서 서버 오류를 강제로 일으키고 클라이언트가 ACK 콜백 안에서 오류를 보는지 확인해.

Progress

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

댓글 0

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

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