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

Socket.IO Client (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

The client API in one block

The browser/Node client (socket.io-client) is a single io() call. It returns a socket that auto-reconnects, supports event subscriptions and emits, and provides callback-based or promise-based acknowledgements. The same SDK works in Node, React Native, and any modern bundler.

Event names are arbitrary strings

Unlike raw WebSocket, you do not roll your own message router. You just socket.on('chat:message', handler) and socket.emit('chat:message', payload). The library maps event names to internal frame types.

Acknowledgements: callback or Promise

Pass a callback as the last argument to emit and the library waits for the server to ack. Use emitWithAck for a Promise-based API. Server-side, your event handler returns a value or array which becomes the ack data. This gives you request-response with no correlation-ID code to write.

Code

Socket.IO client·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

Wire a Socket.IO client to your server from t6l2. Send a chat:message and use both the callback-style and emitWithAck Promise-style acks. Force the server to throw inside the handler — confirm the client sees the error inside the ack callback.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.