C.W.K.
Stream
Lesson 03 of 07 · published

Socket.IO 클라 (JavaScript)

~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-client) 가 단일 io() 호출. auto-reconnect, event 구독 + emit, callback-based 또는 promise-based ACK 지원하는 socket 리턴. 같은 SDK 가 Node, React Native, modern bundler 모두에서 작동.

Event 이름 임의 string

raw WebSocket 과 달리 message router 직접 안 만들어. 그냥 socket.on('chat:message', handler) + socket.emit('chat:message', payload). 라이브러리가 event 이름을 내부 frame type 에 매핑.

Acknowledgement: callback 또는 Promise

emit 의 마지막 인자에 callback 넘기면 라이브러리가 서버 ack 기다림. Promise-based API 위해선 emitWithAck. 서버쪽 event handler 가 값 또는 array 리턴하면 그게 ack data. correlation-ID 코드 안 짜고 request-response 됨.

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 보내고 callback-style + emitWithAck Promise-style ack 둘 다 써. handler 안에서 서버 throw 강제 — 클라가 ack callback 안에서 error 보는지 확인.

Progress

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

댓글 0

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

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