Advertisement
fkudinov

Simple Python web server on sockets

Aug 31st, 2024
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | Source Code | 0 0
  1. import socket
  2.  
  3. HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
  4. PORT = 65432        # Port to listen on (non-privileged ports are > 1023)
  5.  
  6.  
  7. response = """HTTP/1.1 200 OK
  8. Content-Type: text/html; charset=utf-8
  9.  
  10. <html>
  11.   <head>
  12.       <title>My Great Title</title>
  13.   </head>
  14.   <body>
  15.       <h1>Hello from socket</h1>
  16.   </body>
  17. </html>
  18. """
  19.  
  20.  
  21. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  22.     s.bind((HOST, PORT))
  23.  
  24.     while True:
  25.         print("Start listening...")
  26.         s.listen()
  27.  
  28.         conn, addr = s.accept()
  29.         with conn:
  30.             print('Connected by', addr)
  31.             while True:
  32.                 data = conn.recv(1024)        # 1010101110101…
  33.                 print(data.decode("utf-8"))
  34.                 if not data:
  35.                     break
  36.  
  37.                 conn.sendall(response.encode("utf-8"))  # 110101111001…
  38.                 break
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement