Implementing an HTTP server in Python
Knowing the methods that we have reviewed previously, we can implement our own HTTP server. For this task, we could use the bind()
method, which accepts the IP address and port as parameters.
The socket module provides the listen()
method, which allows you to queue up to a maximum of n
requests. For example, we could set the maximum number of requests to 5
with the mysocket.listen(5)
statement.
In the following example, we are using localhost
, to accept connections from the same machine. The port could be 80
, but since you need root privileges, we will use one greater than or equal to 8080
. You can find the following code in the http_server.py
file in the http_server
folder:
import socket
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.bind(('localhost', 8080))
mySocket.listen(5)
while True:
print('Waiting for connections')
(recvSocket, address) = mySocket.accept()
print('HTTP...