close

Python – How to check if socket is still connected

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about Python – How to check if socket is still connected in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

Python – How to check if socket is still connected?

  1. Python – How to check if socket is still connected?

    I've had good results with this variant to check if a socket is closed (negate the result if you want to check if it's still connected):

  2. check if socket is still connected

    I've had good results with this variant to check if a socket is closed (negate the result if you want to check if it's still connected):

Method 1

If the server connection is no longer alive, calling the send method will throw an exception, so you can use a try-exception block to attempt to send data, catch the exception if it’s thrown, and reestablish the connection:

try:
    s.send("some more data")
except:
    # recreate the socket and reconnect
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(host, port)
    s.send("some more data")

Method 2

I’ve had good results with this variant to check if a socket is closed (negate the result if you want to check if it’s still connected):

import logging
import socket


logger = logging.getLogger(__name__)


def is_socket_closed(sock: socket.socket) -> bool:
    try:
        # this will try to read bytes without blocking and also without removing them from buffer (peek only)
        data = sock.recv(16, socket.MSG_DONTWAIT | socket.MSG_PEEK)
        if len(data) == 0:
            return True
    except BlockingIOError:
        return False  # socket is open and reading from it would block
    except ConnectionResetError:
        return True  # socket was closed for some other reason
    except Exception as e:
        logger.exception("unexpected exception when checking if a socket is closed")
        return False
    return False

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read