I have recently built a small HTTP server that can respond with static files like HTML, CSS, JS, etc. This server is built on top of a TCP server.
TCP is a protocol for computers to communicate with one another.
A TCP server typically has:
- A process running.
- It registers a port along with an IP (localhost) to the operating system, which together are called a socket. This socket listens for incoming requests on that port.
- These sockets are logical identifiers maintained by the operating system to forward incoming requests to a particular process running on the computer.
- After successfully registering, any subsequent requests to that socket will be forwarded to that port.
- My process needs to accept the request, read data from it, write back to that request, and then close the connection.
I have built a simple TCP server in C#, which is a process that registers a socket and handles accepting, reading, writing, and closing connections.
Multithreading
- TCP servers are more likely to concurrently execute requests.
- My server initially had a single main thread doing all the work, processing each request one by one as incoming requests are put into a TCP queue by the operating system.
- To enable multithreading, my server delegates the execution of each accepted connection to a separate thread. This allows the main thread to continuously accept new connections while other threads handle processing concurrently.
- Building this software highlights the importance and benefits of multithreading.
Data Interpretation
- Since HTTP is built on top of TCP, to test the server, I use cURL from the command line or access it from a browser.
- After accepting the request, all information is received as a byte stream that we need to read and convert to a string to interpret the requested data.
- In the code, you can notice that I extract the last part of the request URL to determine which file is requested and its type.
Thread Pool
- I need to set up a thread limit; otherwise, I will run out of resources to create new threads and won't be able to reuse already created threads, as the creation and deletion of threads take time and resources.