0

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?

cak3_lover
  • 1,440
  • 5
  • 26
  • 1
    "*shouldn't the error be handled by `try except` ?*" - yes. "*how else do I handle this error without the script being terminated?*" - The script is going to terminate anyway, as you are servicing only 1 client. To service multiple clients, move the `accept()` into an outer loop, and then have a `try except` around your communication loop, so that if/when a client does fail, you can move on to `accept()` the next client. You might also consider handling each client in a separate thread, or at least multiplex them with [`select()`](https://docs.python.org/3/library/select.html#select.select). – Remy Lebeau Jul 01 '22 at 23:29

1 Answers1

0

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

cak3_lover
  • 1,440
  • 5
  • 26