Importing the Socket Module
import socket- Importing Modules: Imports the
socketmodule for working with sockets.
Creating and Configuring the Server Socket
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.bind(('localhost', 8080))- Creating Socket: Creates a TCP socket using
socket.AF_INETfor IPv4 andsocket.SOCK_STREAMfor a stream-oriented connection (TCP). - Binding Socket: Binds the socket to the local address
localhostand port8080.
Listening for Incoming Connections
mySocket.listen(5)- Listening: Configures the socket to listen for incoming connections with a backlog queue size of 5.
Handling Incoming Connections in a Loop
while True:
print('Waiting for connections')
(recvSocket, address) = mySocket.accept()- Infinite Loop: Continuously waits for incoming connections.
- Accepting Connection: Accepts an incoming connection, returning a new socket (
recvSocket) and the address of the client.
Handling HTTP Request and Sending Response
print('HTTP request received:')
print(recvSocket.recv(1024))- Receiving Data: Receives and prints the HTTP request data from the client (up to 1024 bytes).
recvSocket.send(bytes("HTTP/1.1 200 OK\r\n\r\n <html><body><h1>Hello World!</h1></body></html> \r\n",'utf-8'))- Sending Response: Sends an HTTP response to the client indicating a successful status (200 OK) and a simple HTML page.
Closing the Connection
recvSocket.close()- Closing Connection: Closes the socket for the individual connection.
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 request received:')
print(recvSocket.recv(1024))
recvSocket.send(bytes("HTTP/1.1 200 OK\r\n\r\n <html><body><h1>Hello World!</h1></body></html> \r\n",'utf-8'))
recvSocket.close()This script represents a simple HTTP server that listens on localhost:8080. It accepts incoming connections, prints received HTTP requests, sends a basic HTML response, and then closes the connection. Note that this example is minimal and may not handle all aspects of a production-level HTTP server. It’s mainly intended for educational purposes.
Implementing a basic HTTP server in Python can be done using the built-in http.server module. Below is a simple example of how you can create an HTTP server that serves static files from the current directory.
import http.server
import socketserver
# Set the port number
port = 8080
# Choose the handler you want to use
handler = http.server.SimpleHTTPRequestHandler
# Create the server with the specified handler
with socketserver.TCPServer(("", port), handler) as httpd:
print(f"Serving on port {port}")
# Start the server
httpd.serve_forever()Here’s a breakdown of the code:
- Import Necessary Modules:
http.server: Provides basic HTTP server classes.socketserver: Allows the creation of network servers.
- Set the Port Number:
- Define the port on which the server will listen. In this case, it’s set to 8080.
- Choose the Handler:
- Use
http.server.SimpleHTTPRequestHandleras the handler. This handler serves files from the current directory and its subdirectories.
- Use
- Create and Start the Server:
- Use
socketserver.TCPServerto create a TCP server, specifying the host (“” means all available interfaces) and the port. - The
withstatement ensures that the server is properly closed when the script exits. - Print a message indicating that the server is running.
- Call
httpd.serve_forever()to start serving requests indefinitely.
- Use
Save this code in a file (e.g., http_server.py) and run it using:
python http_server.pyYour basic HTTP server will be accessible at http://localhost:8080, and you can navigate to different files and directories within the current directory. This example is suitable for serving static files during development, and for production, you may consider more advanced frameworks like Flask or Django.
Testing the HTTP Server
Shebang and Importing the Socket Module
#!/usr/bin/python
import socket- Shebang and Import: Specifies the shebang line to indicate the Python interpreter to be used. Imports the
socketmodule for working with sockets.
Setting Web Host and Port
webhost = 'localhost'
webport = 8080- Setting Web Host and Port: Defines the target web host (
localhost) and port (8080) to connect to.
Connecting to the Web Server
print("Contacting %s on port %d ..." % (webhost, webport))
webclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
webclient.connect((webhost, webport))- Connection Setup: Prints a message indicating the target host and port. Creates a TCP socket (
webclient) usingsocket.AF_INETfor IPv4 andsocket.SOCK_STREAMfor a stream-oriented connection (TCP). Connects to the specified web host and port.
Sending an HTTP GET Request
webclient.send(bytes("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n".encode('utf-8')))- Sending Request: Sends an HTTP GET request to the web server. The request includes the HTTP version, the requested resource (“/”), and the “Host” header.
Receiving and Printing the Server’s Response
reply = webclient.recv(4096)
print("Response from %s:" % webhost)
print(reply.decode())- Receiving Response: Receives the server’s response, up to 4096 bytes, and stores it in the
replyvariable. - Printing Response: Prints the response from the web server, decoding it from bytes to a UTF-8 string.
Closing the Socket
webclient.close()- Closing Connection: Closes the socket after the communication with the web server is complete.
#!/usr/bin/python
import socket
webhost = 'localhost'
webport = 8080
print("Contacting %s on port %d ..." % (webhost, webport))
webclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
webclient.connect((webhost, webport))
webclient.send(bytes("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n".encode('utf-8')))
reply = webclient.recv(4096)
print("Response from %s:" % webhost)
print(reply.decode())This script acts as a simple HTTP client that connects to a web server (localhost:8080 in this case), sends an HTTP GET request, receives the server’s response, and prints it. Note that this example is minimal and may not handle all aspects of a production-level HTTP client. It’s mainly intended for educational purposes.
