Created
November 21, 2019 18:34
-
-
Save nachonavarro/6a92a1783343d689f146ebf7de4eaaf3 to your computer and use it in GitHub Desktop.
A simple server in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
An extremely simple server. | |
Use Python 3. | |
""" | |
import socket | |
from textwrap import dedent | |
class MySimpleServer: | |
def __init__(self): | |
self.count = 0 | |
print(f'Firing up server... Go to localhost:1234') | |
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
self.socket.bind(('localhost', 1234)) | |
self.socket.listen(1) | |
def run(self): | |
while True: | |
# Step 1: Accept a client's connection | |
client, client_address = self.socket.accept() | |
print(f"Got a request from {client_address}!") | |
# Step 2: Receive client's request | |
request = client.recv(1024) | |
# Step 3: Do stuff with the client's request, e.g. update database. | |
# We're just going to print it. Look at the terminal. | |
print(request.decode('utf-8')) | |
# Step 4: Return a response. | |
response = dedent(f"""\ | |
HTTP/1.1 200 OK | |
Hello, this is the {self.count} request I have received! | |
""").encode() | |
client.sendall(response) | |
client.close() | |
self.count += 1 | |
if __name__ == '__main__': | |
server = MySimpleServer() | |
server.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment