Understanding TCP/UDP, Socket Connections, and Implementing a Socket Connection Pool in Node.js
This article explains the fundamentals of network protocols, the OSI seven‑layer model, TCP three‑handshake and four‑teardown processes, differences between TCP and UDP, socket long‑connections, custom protocol design, and how to implement a reusable socket connection pool in Node.js.
The author introduces the basic concepts of network protocols, starting with the OSI seven‑layer model and mapping common protocols such as IP, TCP, UDP, and HTTP to their respective layers.
It then details the TCP three‑handshake process (SYN, SYN‑ACK, ACK) and the four‑step teardown (FIN, ACK, FIN, ACK), explaining the purpose of each step and the TIME_WAIT state.
A comparison between TCP and UDP follows, highlighting TCP’s reliability and connection‑oriented nature versus UDP’s connectionless, low‑overhead characteristics, and discussing typical use‑cases for each.
The article discusses socket long connections versus short connections, describing how long connections keep a TCP socket alive with heartbeat packets and when they are preferable.
It outlines the design of a custom application‑layer protocol (including heartbeat format, message header with length, and JSON payload) and shows how to serialize and parse messages.
Next, the concept of a socket connection pool is introduced: a pool maintains a set of reusable long‑living sockets, tracks idle, active, and waiting queues, removes invalid sockets, and creates new ones as needed.
The author presents a Node.js example using the generic-pool library, showing directory structure, pool initialization, and usage with the custom protocol, accompanied by logs that demonstrate socket reuse.
Finally, a brief source‑code analysis points to the Pool.js implementation, describing its constructor, acquire method, and how it manages resources, encouraging readers to explore the code further.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.