Beispiel #1
0
class Client:
    def __init__(self,
                 host: str,
                 port: int,
                 connection_type: SocketKind = SOCK_STREAM,
                 connection_family: AddressFamily = AF_INET,
                 *args,
                 **kwargs):
        self.__host = host
        self.__port = port
        self.__address = (
            host,
            port,
        )
        self.__conn_type = connection_type
        self.__conn_family = connection_family
        self.__to_stop = False
        self.user = "******"
        self.__message_handler = MessageHandler(PROTOCOLS_PATH, self.user)

    def run(self) -> None:
        # ToDo use ZeroMQ or socket + select (lib)
        with socket(family=self.__conn_family, type=self.__conn_type) as s:
            if not self.__conn_family == AF_INET:
                raise ConnectionError(
                    f"Unknown connection family. "
                    f"Expected: AF_INET. Actual: {str(self.__conn_family)}")
            if self.__conn_type == SOCK_STREAM:
                try:
                    s.connect(self.__address)
                except ConnectionRefusedError as exc:
                    raise ConnectionError(
                        f"Server is not running or unknown ServerError occurred. Error: {exc}"
                    )
                self.__message_handler.communicator = s
                self.__start_chat_session(s)
            else:
                raise ConnectionError(
                    f"Unknown connection type. "
                    f"Expected: SOCK_STREAM. Actual: {str(self.__conn_type)}")

    def __start_chat_session(self, sock: socket) -> None:
        while not self.__to_stop:
            received_data = sock.recv(1024)
            self.__message_handler.handle_message(received_data)

            message = input('Write something to send to the server: ')
            to_send = dict(
                username=self.user,
                send_to="Petrov12345",
                message=message,
            )
            self.__message_handler.send_user_message(
                to_send, temporary_communicator=sock)

    def stop(self) -> None:
        """ Switch-flag for stopping the client """
        self.__to_stop = True
Beispiel #2
0
class Server:
    def __init__(self,
                 port: int,
                 host: str = "",
                 connection_type: SocketKind = SOCK_STREAM,
                 connection_family: AddressFamily = AF_INET,
                 *args,
                 **kwargs):
        self.__host = host
        self.__port = port
        self.__address = (
            host,
            port,
        )
        self.__conn_type = connection_type
        self.__conn_family = connection_family
        self.__to_stop = False
        self.__message_handler = MessageHandler(PROTOCOLS_PATH)

    def run(self) -> None:
        # ToDo make the server work with multiple clients
        with socket(family=self.__conn_family, type=self.__conn_type) as s:
            if not self.__conn_family == AF_INET:
                raise ConnectionError(
                    f"Unknown connection family. "
                    f"Expected: AF_INET. Actual: {str(self.__conn_family)}")
            if self.__conn_type == SOCK_STREAM:
                s.bind(self.__address)
                s.listen()
                print("Server started and waiting for connections...")
                conn, addr = s.accept()
                self.__message_handler.communicator = conn
                with conn:
                    print(f"Connection established with {addr}")
                    self.__message_handler.send_precence_request_message()
                    while not self.__to_stop:

                        received_message = conn.recv(4096)
                        self.__message_handler.handle_message(received_message)
                        # if not received_message:
                        #     break
                        # print(f"Received data from client: {received_message.decode(encoding='utf-8')}")
                        # conn.sendall(received_message)
            else:
                raise ConnectionError(
                    f"Unknown connection type. "
                    f"Expected: SOCK_STREAM. Actual: {str(self.__conn_type)}")

    def stop(self) -> None:
        """ Switch-flag for stopping the server """
        self.__to_stop = True