Search code examples
pythonsocketstcp

How I can check connection correctly


I have a boolean variable:

is_conected = False

And I have this part of code:

def start(self, host='localhost', port=32767): 
    self.__connection.bind((host, port))
    self.__connection.listen(5) 

def send_frame(self, frame: str): 
    if not self.__connection.send(bytes(frame, encoding='utf-8')):
        raise RuntimeError("Connection broken.") 

def recieve_frame(self) -> str:
    socket, adress = self.__connection.accept()
    str(__data) = socket.recv(1024)  
    __frame_buffer.append(__data)

Where I need to put If... Else, for checking, if someone connected or not? And what kind of condition I need to use?

The whole code:

    import socket


class TCPServer():
    __frame_buffer = list() 
    __connection = None 
    is_conected = True 

    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(TCPServer, cls).__new__(cls)
        return cls.instance

    def __init__(self): 
        self.__connection = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM)

    def start(self, host='localhost', port=32767): 
        #        """ Start server """
        self.__connection.bind((host, port))
        self.__connection.listen(5) 

    def send_frame(self, frame: str):        
    # """ Send frame """
        if not self.__connection.send(bytes(frame, encoding='utf-8')): 
            raise RuntimeError("Connection broken.") 

    def recieve_frame(self) -> str: 
        socket, adress = self.__connection.accept() 
        str(__data) = socket.recv(1024)  
        __frame_buffer.append(__data) 

    def get_frame(self) -> str:
        if self.__frame_buffer:
            self.__frame_buffer.pop(0)

server = TCPServer()
while True:
    if server.is_conected:
        server.send_frame(str(input("String to send")))
    print(server.get_frame())

That's the whole code. I don't write a more part of it, only a send and recieve frame function. So, that's kinda a school project for me and I'm not too good in working with any kind of connection or protocols


Solution

  • This is how the server generally works

    with socket(AF_INET, SOCK_STREAM) as s:
        s.bind((HOST, PORT)) 
        s.listen() # Start listening
        while True:
            conn, addr = s.accept() # Accept connection request
            Connected = True # You are connected
            try: 
                #Work with connection
            except:
                 Connected = False
    

    Figure out how you can do this with your code