-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti_echo_server.py
More file actions
44 lines (35 loc) · 1.11 KB
/
multi_echo_server.py
File metadata and controls
44 lines (35 loc) · 1.11 KB
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
41
42
43
44
#!/usr/bin/env python3
import socket, time
from multiprocessing import Process
HOST = ""
PORT = 8001
BUFFER_SIZE = 1024
def handle_conn(conn):
# collect sent data up to our BUFFER_SIZE
full_data = conn.recv(BUFFER_SIZE)
# wait before sending response and looping again
time.sleep(0.5)
# respond with whatever we were sent
conn.sendall(full_data)
# close the connection
conn.close()
def main():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# for q3
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# bind the socket to our specified address
s.bind((HOST, PORT))
# set socket to listen mode so that it can accept connections
# (argument is how many pending connections to sit on before refusing new ones)
s.listen(2)
# loop forever until program is shut down
while True:
# accept connection
conn, addr = s.accept()
print("Connected by", addr)
p = Process(target=handle_conn, args=(conn,))
p.daemon = True
p.start()
p.join()
if __name__ == "__main__":
main()