Home > Mobile >  Connection reset by peer error showing despite using try
Connection reset by peer error showing despite using try

Time:07-09

I have a server like this:

HOST = "127.0.0.1" 
PORT = 6000 

try:
    s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen()

    conn, addr = s.accept()
    print("Connection Established!");

    while True:
        data = conn.recv(1024)
        print(data.decode())
        conn.sendall(data)
        
except:
    print("Error! Connection terminated!")

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?

CodePudding user response:

From this answer I found the following solution:

from socket import error as SocketError,socket,AF_INET,SOCK_STREAM

HOST = "127.0.0.1"
PORT = 6000 

while True:
    try:
        s= socket(AF_INET, SOCK_STREAM)
        s.bind((HOST, PORT))
        s.listen()

        conn, addr = s.accept()

        while True:
            data = conn.recv(1024)
            
    except SocketError as e:
        print("Connection Terminated! Restarting...")

but I recommend reading the comment by @Remy Lebeau before applying this

  • Related