Skip to content

Sockets

An endpoint for communication between two machines over a network.

Identified by: IP address + Port number = Socket Example: 192.168.1.1:8080

A connection = pair of sockets (client socket + server socket)

Types of Sockets

TypeProtocolCharacteristics
Stream SocketTCPReliable, ordered, connection-oriented
Datagram SocketUDPUnreliable, connectionless, fast
Raw SocketIP/ICMPDirect access to lower layers, used in tools like ping

Socket Lifecycle — Server vs Client

SERVER                          CLIENT
  │                                │
socket()                        socket()
  │                                │
bind()                             │
  │                                │
listen()                           │
  │                                │
accept()  ◄────── connect() ───────┤
  │                                │
read()/write() ◄──────────────► read()/write()
  │                                │
close()                         close()

Key calls:

  • socket() — create socket
  • bind() — attach to IP + port (server only)
  • listen() — wait for connections (server only)
  • accept() — accept incoming connection (blocks until client connects)
  • connect() — client initiates connection
  • read()/write() or send()/recv() — exchange data
  • close() — terminate

Port Numbers

RangeTypeExample
0–1023Well-known80 (HTTP), 443 (HTTPS), 22 (SSH)
1024–49151Registered3306 (MySQL), 6379 (Redis)
49152–65535EphemeralAssigned to clients dynamically

When your browser connects to google.com:443 — Google uses port 443, your browser gets a random ephemeral port.

WebSockets (Different Thing)

  • Built on top of HTTP, then upgrades to persistent connection.
  • Full duplex — server can push data to client anytime.
  • Used in: chat apps, live feeds, collaborative tools.
  • Regular sockets are OS-level; WebSockets are application-level protocol.

Key Concepts

Blocking vs non-blocking:

  • Blocking — accept() waits until a client connects, halts execution.
  • Non-blocking — returns immediately, you poll or use callbacks.

Multiplexing:

  • select() / epoll() — monitor multiple sockets at once.
  • How Node.js handles thousands of connections on a single thread.