-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp_socket_server_1_nonblock_loop.py
More file actions
executable file
·53 lines (47 loc) · 1.58 KB
/
tcp_socket_server_1_nonblock_loop.py
File metadata and controls
executable file
·53 lines (47 loc) · 1.58 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
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python3
"""TCP-сервер: Неблокирующие сокеты + бесконечный цикл проверки"""
import socket
HOST = 'localhost'
PORT = 12345
serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv_sock.bind((HOST, PORT))
serv_sock.listen(1)
serv_sock.setblocking(False) # Important!
connections = []
while True:
try:
# print("Try to accept a new connection...")
sock, addr = serv_sock.accept()
sock.setblocking(False)
print("Connected by", addr)
connections.append((sock, addr))
except BlockingIOError:
# print("No connections are waiting to be accepted")
pass
for sock, addr in connections.copy():
print("Try to receive data from:", sock, addr)
try:
data = sock.recv(1024)
except ConnectionError:
print(f"Client suddenly closed while receiving from {addr}")
connections.remove((sock, addr))
sock.close()
continue
except BlockingIOError:
# No data received
continue
print(f"Received: {data} from: {addr}")
if not data:
connections.remove((sock, addr))
sock.close()
print("Disconnected by", addr)
continue
data = data.upper()
print(f"Send: {data} to: {addr}")
try:
sock.sendall(data)
except ConnectionError:
print(f"Client suddenly closed, cannot send to {addr}")
connections.remove((sock, addr))
sock.close()
continue