Implementing an HTTP server in Python
Knowing the methods that we have reviewed previously, we could 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:
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() Â ...