basic server in python

To create a basic server in Python, you can use the sockets and networking libraries. Here's an example using the HTTP protocol:

main.py
import socket

HOST, PORT = '', 8888

# create a TCP socket
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)

print(f'Serving HTTP on {HOST} port {PORT}...')

while True:
    # wait for a client connection
    client_connection, client_address = listen_socket.accept()
    # receive the request data
    request_data = client_connection.recv(1024)
    print(request_data.decode('utf-8'))

    # create the HTTP response
    http_response = """\
HTTP/1.1 200 OK

Hello, World!
"""

    # send the HTTP response
    client_connection.sendall(http_response.encode('utf-8'))
    # close the connection
    client_connection.close()
770 chars
31 lines

This creates a TCP socket and listens for incoming connections on port 8888. When a client connects, it receives the client connection and decodes the request data. It then creates an HTTP response and sends it back to the client, before closing the connection.

gistlibby LogSnag