Implemeting a basic Web Server


What is a web server?


Web server is a networking server that sits on a physical server waiting for client requests.
The Web server creates a listening socket and starts accepting new connections in a loop. The client initiates a TCP connection and, after successfully establishing it, the client sends an HTTP request to the server and the server responds with an HTTP response that gets displayed to the user. To establish a TCP connection both clients and servers use sockets.

Sockets



A good understanding of sockets can be gained from reference [1] link.

Simply, client sockets can be used to send and receive data, where as server sockets are used to create a client socket.

In this case, the socket is bound to port 8888, and host=“ ” specifies that the socket is reachable by any address the machine happens to have. 
 
Since low numbers are reserved for well knows ports (like 80 for HTTP), I used a high number (8888).
The socket is destroyed after one receive and send in this case. (listen(1))

In a web server it creates a “server socket”. The “server socket” produces “client sockets”.

Each “client socket” is created in response to some other “client” socket doing a  connect() to the host and port we’re bound to.(in this case “localhost” and 8888)

After creating the “client socket” it goes back to listening for more connections. The two “clients” then use a dynamically allocated port which will be recycled when the conversation ends.




Browser


The browser can be simulated using “telnet” command on command line.
$ telnet localhost 8888

Browser connects you to localhost when the message is diplayed.
Trying 127.0.0.1 …
Connected
to localhost.

Before your browser can send a HTTP request, it establishes a TCP connection with the Web server. Then it sends an HTTP request over the TCP connection to the server and waits for the server to send an HTTP response back.
When the browser receives the response it displays it.

This is a python code for a basic web server, which returns and displays in your browser “This is the server respose! :)” for any request.



to run:

python pythonWebServer.py 

in another terminal:

telnet localhost 8888
GET /hello HTTP/1.1

(to whatever you type, it will give the following message)





Reference:

1 https://docs.python.org/2/howto/sockets.html
2 https://ruslanspivak.com/lsbaws-part1/

Comments

Popular posts from this blog

Save recorded data with hackRF to a .raw file

Listen to FM radio with HackRF and SDR