-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho_server.py
More file actions
executable file
·37 lines (29 loc) · 1006 Bytes
/
echo_server.py
File metadata and controls
executable file
·37 lines (29 loc) · 1006 Bytes
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
#!/usr/bin/env python3
import socket, time
HOST = ""
PORT = 8001
BUFFER_SIZE = 1024
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)
# 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()
if __name__ == "__main__":
main()