-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecho_server.py
41 lines (30 loc) · 1.05 KB
/
echo_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/bin/env python3
import socket
HOST = '127.0.0.1'
PORT = 5000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen()
print(f'Server is listening on {HOST}:{PORT}')
try:
while True:
conn, addr = s.accept()
with conn:
print(f'Connected by {addr}')
data = conn.recv(1024)
if not data:
break
response_body = data.decode('utf-8', errors='replace')
response_header = (
"HTTP/1.1 200 OK\r\n"
"Content-type: text/plain\r\n"
f"Content-Lenght: {len(response_body)}\r\n"
"Connection: close\r\n"
"\r\n"
)
conn.sendall(response_header.encode('utf-8') + response_body.encode('utf-8'))
except KeyboardInterrupt:
print("\nServer is shutting down...")
s.close()
exit(1)