Networking Notes With Code
Networking Notes With Code
TCP :
UDP :
HTTP 1 :
HTTP 1.1 :
HTTP/2 :
-------------------------------------------------------------------------
Websocket :
Short Poling :
Long Polling :
WebRTC :
XMPP :
Webhook :
Detailed :
● UDP is a connectionless protocol that does not establish a reliable and ordered
connection between two endpoints.
● It provides unreliable delivery, as it does not guarantee that all packets will be received or
in what order they will be received.
● UDP does not include built-in error detection or recovery mechanisms, leaving error
handling to the applications themselves.
● It does not have flow control mechanisms to manage the rate of data transmission.
● UDP does not incorporate congestion control mechanisms and does not intervene in
preventing network congestion.
● UDP is commonly used in applications where real-time or fast transmission is crucial,
such as video streaming, online gaming, DNS lookup, and Voice over IP (VoIP).
It's important to note that TCP and UDP are designed for different purposes, and the choice of
protocol depends on the specific requirements of the application or service being used.
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main() {
int serverSocket, clientSocket;
struct sockaddr_in serverAddress, clientAddress;
char buffer[BUFFER_SIZE];
// Create socket
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket < 0) {
std::cerr << "Error creating socket." << std::endl;
return 1;
}
while (true) {
socklen_t clientLength = sizeof(clientAddress);
TCP Client(node.js) :
TCP Client(c++) :
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main() {
int clientSocket;
struct sockaddr_in serverAddress;
char buffer[BUFFER_SIZE];
// Create socket
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket < 0) {
std::cerr << "Error creating socket." << std::endl;
return 1;
}
// Connect to server
if (connect(clientSocket, (struct sockaddr *)&serverAddress,
sizeof(serverAddress)) < 0) {
std::cerr << "Error connecting to server." << std::endl;
return 1;
}
std::cout << "Connected to server." << std::endl;
// Close socket
close(clientSocket);
return 0;
}
UDP Server(node.js) :
UDP Server(c++) :
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main() {
int serverSocket;
struct sockaddr_in serverAddress, clientAddress;
char buffer[BUFFER_SIZE];
// Create socket
serverSocket = socket(AF_INET, SOCK_DGRAM, 0);
if (serverSocket < 0) {
std::cerr << "Error creating socket." << std::endl;
return 1;
}
std::cout << "Server listening on port " << PORT << std::endl;
while (true) {
socklen_t clientLength = sizeof(clientAddress);
return 0;
}
UDP Client(node.js) :
UDP Client(c++) :
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main() {
int clientSocket;
struct sockaddr_in serverAddress;
char buffer[BUFFER_SIZE];
// Create socket
clientSocket = socket(AF_INET, SOCK_DGRAM, 0);
if (clientSocket < 0) {
std::cerr << "Error creating socket." << std::endl;
return 1;
}
// Close socket
close(clientSocket);
return 0;
}
HTTP/1: Suppose you want to load a webpage that consists of an HTML file, CSS
stylesheets, JavaScript files, and images. In HTTP/1, each resource requires a
separate TCP connection. So, when you make a request for the HTML file, the
connection is established, the file is transferred, and then the connection is closed.
The same process is repeated for each resource. This leads to a lot of overhead and
slower page loading times. For example, if the HTML file takes longer to load, it will
block subsequent requests for other resources, causing delays.
HTTP/2: With HTTP/2, the major upgrade was the introduction of multiplexing.
Instead of relying on separate connections for each request, HTTP/2 allows multiple
requests and responses to be sent concurrently over a single connection. This
enables efficient use of network resources and reduces latency. For example, when
you request a webpage in HTTP/2, all the resources can be sent over the same
connection simultaneously, significantly improving the page loading speed.
HTTP/3: HTTP/3 is the next major version after HTTP/2 and is based on the QUIC
protocol. The key difference in HTTP/3 is the use of the QUIC transport protocol
instead of TCP. QUIC is designed to address the limitations of TCP, such as
head-of-line blocking. It utilizes UDP (User Datagram Protocol) and includes built-in
encryption. HTTP/3 retains the multiplexing feature of HTTP/2, allowing concurrent
requests and responses. The main advantage of HTTP/3 is improved performance
and reduced latency due to the use of QUIC.
QUIC: QUIC (Quick UDP Internet Connections) is a separate protocol from HTTP,
although it is often used as the underlying transport protocol for HTTP/3. QUIC is
built on top of UDP and includes features like multiplexing, encryption, and reduced
latency. It eliminates head-of-line blocking by allowing independent streams of data
to be transmitted concurrently over a single connection. QUIC also provides built-in
security with encryption. It is designed to improve performance for web applications
by reducing connection setup times and improving data transfer efficiency.
In TCP, data is transmitted in the form of packets, and these packets need to be received
in the correct order to reconstruct the original data. Head-of-line blocking refers to a
packets to be held up until the missing packet is received or retransmitted. This can
result in a delay in the delivery of subsequent packets and cause performance issues.In
the context of HTTP/1 and HTTP/1.1, which use a separate TCP connection for each
response for a particular resource blocks subsequent requests for other resources. For
example, if a web page consists of multiple resources such as images, CSS, and JavaScript files,
and one of these resources experiences a delay in the response, it holds up the delivery of
subsequent requests, even if they could be processed independently. As a result, the overall
parallelism and efficient utilisation of network resources. This problem was addressed and
improved in later versions like HTTP/2 and HTTP/3, which introduced multiplexing and other
Websocket :
On the server side, you can use libraries such as ws for Node.js or frameworks like
Socket.IO to handle WebSocket connections, events, and message routing. These
server-side components manage the WebSocket handshake, connection
management, and the exchange of messages between the client and server.
On the client side, you can use JavaScript WebSocket APIs, such as the WebSocket
object in modern web browsers or WebSocket libraries for other platforms, to
establish and manage WebSocket connections. The client-side code can define
event handlers for different WebSocket events, such as connection establishment,
message receipt, and connection closure.
With WebSocket, you can build real-time, interactive applications that require
continuous communication between clients and servers, enabling rich user
experiences and efficient data transfer in various domains.
We can also create websocket server and client connection to demonstrate push notification
functionality which is a common part of any real world software .
Long Polling :
Long Polling is a technique where the client sends a request to the server and the
server holds the request open until new data is available or a timeout occurs. If new
data is available, the server responds with the updated data, and the client
immediately sends another request to maintain a continuous connection. This
approach enables real-time updates without the need for constant polling from the
client.
app.listen(3000, () => {
console.log('Long Polling server listening on port 3000');
});
WebSocket protocol and long polling are both techniques used to achieve real-time,
bidirectional communication between a client (usually a web browser) and a server.
However, they differ significantly in their approach and behavior:
Protocol:
● WebSocket: WebSocket is a standardized communication protocol that
provides full-duplex, bidirectional communication channels over a
single TCP connection. It allows both the client and server to send and
receive messages at any time during the connection's lifespan.
● Long Polling: Long polling is not a standardized protocol; instead, it is a
technique that uses HTTP. The client sends an HTTP request to the
server, and the server keeps the request open until new data is
available or a timeout occurs. When data is available, the server
responds to the client's request with the new data, and the client
immediately processes it and sends another request to keep the
connection open.
Connection Management:
● WebSocket: WebSockets establish a single persistent connection
between the client and the server that remains open as long as both
parties want it to stay open. This allows real-time data to be sent in
both directions without the need to repeatedly open and close
connections.
● Long Polling: With long polling, the connection is continuously opened
and closed in a request-response fashion. Each time the client receives
a response from the server, it immediately sends another request to
keep the connection open. This process is repeated in a loop, allowing
the server to push data to the client when it becomes available.
Short Polling :
Short polling is a client-server communication mechanism where the client
periodically sends requests to the server at fixed intervals to check for updates. The
server responds to each request with the current data, regardless of whether it has
been updated since the last request. The client then processes the response and
decides whether to make subsequent requests for updates.
function fetchData() {
fetch('http://localhost:3000/data')
.then((response) => response.json())
.then((data) => {
console.log('Received data:', data);
The client establishes an HTTP connection with the server using the SSE
protocol.
The server responds with an SSE stream by setting the response content type
to text/event-stream and sending a series of event messages to the client.
The SSE stream consists of individual events, each separated by a newline
character (\n).
Each event message contains one or more event fields, such as event, data,
id, and retry, each with its respective value.
The server can send events at any time by writing event messages to the SSE
stream. The client receives these events as they are pushed by the server.
The client's SSE API listens for incoming events and triggers event handlers
when new events are received.
The client can perform actions based on the received events, such as
updating the user interface or executing specific logic.
res.write('event: server-time\n');
res.write(`data: ${eventData}\n\n`);
}, 1000);
app.use(express.json());
let todos = [
{ id: 1, task: 'Learn Node.js', completed: false },
{ id: 2, task: 'Read a book', completed: true }
];
// Update a todo
app.put('/todos/:todoId', (req, res) => {
const todoId = parseInt(req.params.todoId);
const { task, completed } = req.body;
const todo = todos.find(todo => todo.id === todoId);
if (todo) {
todo.task = task;
todo.completed = completed;
res.json(todo);
} else {
res.status(404).json({ error: 'Todo not found' });
}
});
// Delete a todo
app.delete('/todos/:todoId', (req, res) => {
const todoId = parseInt(req.params.todoId);
const index = todos.findIndex(todo => todo.id === todoId);
if (index !== -1) {
todos.splice(index, 1);
res.sendStatus(204);
} else {
res.status(404).json({ error: 'Todo not found' });
}
});
gRPC :
GraphQL :
GraphQL is a query language for your API, allowing clients to request the exact data
they need and nothing more. It was developed by Facebook and provides a more
efficient and flexible alternative to traditional RESTful APIs. With GraphQL, clients
can specify the structure of the response, enabling them to retrieve multiple
resources in a single request and avoid over-fetching or under-fetching data.
SOAP :
Webhook :
DASH :