HTTP

Overview

concept map of HTTP
Figure 1: Concept Map

Terms defined: client, Domain Name System (DNS), HTTP request, HTTP response, HyperText Transfer Protocol (HTTP), Internet Protocol, IP address, port, server, socket, Transmission Control Protocol

Outline

Using Sockets

"""Basic socket server."""

import socketserver


CHUNK_SIZE = 1024
SERVER_ADDRESS = ("localhost", 5000)


class MyHandler(socketserver.BaseRequestHandler):
    def handle(self):
        data = self.request.recv(CHUNK_SIZE)
        cli = self.client_address[0]
        msg = f"server received {len(data)} bytes from {cli}"
        print(msg)
        print(data)
        self.request.sendall(bytes(msg, "utf-8"))


if __name__ == "__main__":
    server = socketserver.TCPServer(SERVER_ADDRESS, MyHandler)
    server.serve_forever()
echo "testing" | nc 127.0.0.1 5000

HTTP Request and Response

GET /index.html HTTP/1.1
Accept: text/html
Accept-Language: en, fr
If-Modified-Since: 16-May-2024
HTTP/1.1 200 OK
Date: Thu, 16 June 2023 12:28:53 GMT
Content-Type: text/html
Content-Length: 53

<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
from http.server import BaseHTTPRequestHandler, HTTPServer

PAGE = """<html><body><p>path: {path}</p></body></html>"""

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        page = PAGE.format(path=self.path)
        content = bytes(page, "utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(content)))
        self.end_headers()
        self.wfile.write(content)

if __name__ == "__main__":
    server_address = ("localhost", 5000)
    server = HTTPServer(server_address, RequestHandler)
    server.serve_forever()