I have a server like this:
JavaScript
x
19
19
1
HOST = "127.0.0.1"
2
PORT = 6000
3
4
try:
5
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
6
s.bind((HOST, PORT))
7
s.listen()
8
9
conn, addr = s.accept()
10
print("Connection Established!");
11
12
while True:
13
data = conn.recv(1024)
14
print(data.decode())
15
conn.sendall(data)
16
17
except:
18
print("Error! Connection terminated!")
19
but the error of
ConnectionResetError: [Errno 104] Connection reset by peer
still occurs on client disconnection, shouldn’t the error be handled by try except
?
If not how else do I handle this error without the script being terminated?
Advertisement
Answer
From this answer I found the following solution:
JavaScript
1
19
19
1
from socket import error as SocketError,socket,AF_INET,SOCK_STREAM
2
3
HOST = "127.0.0.1"
4
PORT = 6000
5
6
while True:
7
try:
8
s= socket(AF_INET, SOCK_STREAM)
9
s.bind((HOST, PORT))
10
s.listen()
11
12
conn, addr = s.accept()
13
14
while True:
15
data = conn.recv(1024)
16
17
except SocketError as e:
18
print("Connection Terminated! Restarting...")
19
but I recommend reading the comment by @Remy Lebeau before applying this