Appearance
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
| Type | Protocol | Characteristics |
|---|---|---|
| Stream Socket | TCP | Reliable, ordered, connection-oriented |
| Datagram Socket | UDP | Unreliable, connectionless, fast |
| Raw Socket | IP/ICMP | Direct 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 socketbind()— attach to IP + port (server only)listen()— wait for connections (server only)accept()— accept incoming connection (blocks until client connects)connect()— client initiates connectionread()/write()orsend()/recv()— exchange dataclose()— terminate
Port Numbers
| Range | Type | Example |
|---|---|---|
| 0–1023 | Well-known | 80 (HTTP), 443 (HTTPS), 22 (SSH) |
| 1024–49151 | Registered | 3306 (MySQL), 6379 (Redis) |
| 49152–65535 | Ephemeral | Assigned 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.