We live in a world of Ethernet frames and data packets zooming over the internet at fast speeds. These packets usually use UDP and TCP protocols. You can connect with servers and exchange data for mobile apps, typically using REST APIs to fetch data, or get streaming data from services like Netflix.
It all happens over the internet using Ethernet frames, which let us exchange information between devices. This process is generally the same whether you use TCP or UDP. Here is some Python code to see how it works. Every coding language, Python, Java, JavaScript, or C, handles this similarly.
To start, we'll use Python because it shows everything nicely on one screen. We'll be using Python 3.7+ and import the Socket module, which lets us bind to ports and accept incoming connections. This setup will allow a read and write scenario, like building your own web framework that supports HTTP, WebSockets, MQTT, or any protocol you want to create.
So, an Ethernet frame, when routed correctly, ensures data gets to its destination. First, we import Socket, define a host and port (localhost or 0.0.0.0 for IPv4), and set up a listening socket. The address family (AF_INET) will be IPv4.
The streaming socket lets data flow bidirectionally. We set socket options to manage data buffering and port reusability, then bind and start listening for incoming connections on port 8888. When a client makes a connection, we receive and print the data, then respond with "200 OK" and "Hello world." Optionally each connection is left open or is closed.
This is a basic example of how a web server handles API calls using TCP. Now, let's start a minimal HTTP web server on my laptop, running Python. We'll accept requests on port 8888, print the request, and respond with "Hello world." Run the server and test it by sending a request, and we'll get a response back. You can continue making API calls because the server keeps listening for new ones.
Each new connection gets a unique client port, thanks to the kernel's management. This setup allows multiple connections and data exchanges. You can customize the server to manage different types of data and requests.
With just 23 lines of code, you can create a functional server and start building more complex APIs.