0

Need to catch socket error while sending data, my code catches error the second time after disconnection, first time send is not throwing exception. Is this the right way to do it. Any way that I can achieve it?

def send_message(msg, inst):
    msg = msg.encode(FORMAT)
    try:
        client[inst].send(msg)
        print(f"Socket error {msg} {inst}")

    except socket.error:
        client[inst].close()
        print(f"Connection closed, moving on {msg} {inst}")
        client[inst+1].send(msg)
  • This is how TCP works. `send()` doesn't wait for the data to be received, it returns immediately. If the receiver has closed the connection, it sends a `RST` response to the data, which updates the socket state, and this is checked the next time you call `send()`. – Barmar Jul 20 '21 at 20:39
  • Thanks Barmar for the quick response, I need to know if the socket is disconnected at the point of sending, how do I achieve that? Is there a way to check if the socket is disconnected even before trying to send? – Abhinav Wadhwa Jul 20 '21 at 20:42

0 Answers0