Ejemplo n.º 1
0
class ServerThread(threading.Thread):

    sock: socket.socket
    _reader: Reader
    _sender: Sender
    _coder: Coder
    logger: Logger

    def __init__(self, sock: socket.socket, coder: Coder, logger: Logger):
        super().__init__()
        self.sock = sock
        self._coder = coder
        self.logger = logger

    def run(self):
        self._reader = TCPReader(self.sock, self._coder)
        self._sender = TCPSender(self.sock, self._coder)

        client_handler = ClientHandler(self._sender, self.logger)
        for line in self._reader.read():
            try:
                invoker = CommandInvoker()
                invoker.set_receiver(client_handler)
                invoker.unserialize(line.decode())
                invoker.send_all()
            except DescribedException as e:
                msg = str(e)
                response = {
                    'type': 'report',
                    'status': 'error',
                    'describe': e.describe(),
                    'message': msg
                }
                self._sender.send(json.dumps(response).encode())
Ejemplo n.º 2
0
 def __init__(self, client: socket, save_path: Path, logger: Logger):
     super().__init__()
     self.client = client
     self.save_path = save_path
     self.reader = TCPReader(self.client, self.coder)
     self.sender = TCPSender(self.client, self.coder)
     self.logger = logger
Ejemplo n.º 3
0
def main():
    args = _arg_parser_factory().parse_args()

    msg: str = args.msg
    use_udp: bool = args.udp
    host: str = args.host
    port: int = args.port

    coder = Base85Coder()
    logger = ConsoleLogger()

    # create socket
    if use_udp:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sender = UDPSender(sock, (host, port), coder)
        reader = UDPReader(sock, coder)
    else:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port))
        sender = TCPSender(sock, coder)
        reader = TCPReader(sock, coder)

    sender.send(b'')
    sender.send(b'msg:' + msg.encode())

    for line in reader.read():
        logger.log(line.decode())
        reader.close()
Ejemplo n.º 4
0
    def run(self):
        self._reader = TCPReader(self.sock, self._coder)
        self._sender = TCPSender(self.sock, self._coder)

        client_handler = ClientHandler(self._sender, self.logger)
        for line in self._reader.read():
            try:
                invoker = CommandInvoker()
                invoker.set_receiver(client_handler)
                invoker.unserialize(line.decode())
                invoker.send_all()
            except DescribedException as e:
                msg = str(e)
                response = {
                    'type': 'report',
                    'status': 'error',
                    'describe': e.describe(),
                    'message': msg
                }
                self._sender.send(json.dumps(response).encode())
Ejemplo n.º 5
0
class TCPThreadingEcho(ThreadingEcho):

    sock: socket.socket
    coder: Coder
    sender: Sender

    def __init__(self, sock: socket.socket, coder: Coder):
        super().__init__()
        self.sock = sock
        self.coder = coder

    def get_reader(self) -> Reader:
        client, _ = self.sock.accept()
        self.sender = TCPSender(client, self.coder)
        return TCPReader(client, self.coder)

    def get_sender(self) -> Sender:
        return self.sender

    def close(self):
        self.sender.close()
Ejemplo n.º 6
0
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    args = _arg_parser_factory().parse_args()
    file_path = Path(args.file)

    host = args.host
    port = args.port

    sock.connect((host, port))
    logger: Logger = ConsoleLogger()
    coder = Base85Coder()

    sender = TCPSender(sock, coder)
    reader = TCPReader(sock, coder)

    if not file_path.exists():
        logger.error(f'{str(file_path)} is not exists.')
        exit(-1)

    if file_path.is_file():
        files = [file_path]
        base_path = file_path.parent
    else:
        files = list(file_path.glob('./**/*.*'))
        base_path = file_path

    file_sender = FileSender(sender)

    # show all the files
    logger.log('The following files will be uploaded:')
    for file in files:
        logger.log(str(file))

    proceed = input('proceed?(y/N):').lower() == 'y'
    if not proceed:
        logger.info('Operation stopped by user.')
        exit(0)

    for file in files:
        file_sender.send_file(file, base_path)

    file_sender.close()

    for response in reader.read():
        if response == b'ok':
            logger.info('All file transmission has been done.')
        elif response.startswith(b'error'):
            logger.error(response.decode())
        else:
            logger.error('Unknown error occurred.')
        reader.close()
Ejemplo n.º 7
0
class ThreadingFileReceiver(threading.Thread):
    client: socket
    save_path: Path
    coder: Coder = Base85Coder()
    logger: Logger

    def __init__(self, client: socket, save_path: Path, logger: Logger):
        super().__init__()
        self.client = client
        self.save_path = save_path
        self.reader = TCPReader(self.client, self.coder)
        self.sender = TCPSender(self.client, self.coder)
        self.logger = logger

    def run(self):
        self.logger.info(f'Starting to receive files from the client.')
        file_receiver = FileReceiver()
        try:
            for line in self.reader.read():
                command, arg = self._get_command(line)

                if command == b'file':
                    filename = arg.decode()
                    file_path = self.save_path / Path(filename)
                    file_path.parent.mkdir(parents=True, exist_ok=True)
                    file_receiver.new_file(file_path)
                    self.logger.info(
                        f'Starting to receive new file {filename}')
                elif command == b'chunk':
                    chunk = arg
                    file_receiver.recv_chunk(chunk)
                    self.logger.debug(
                        f'Received chunk of file.({len(chunk)} bytes)')
                elif command == b'close':
                    break
                else:
                    raise UnknownCommand(command)

            # no error occurred.
            self.sender.send(b'ok')
            self.logger.info('All file transmission has been done.')

        except Exception as e:
            msg = str(e)
            self._send_error(msg)
            self.logger.error(msg)

        finally:
            file_receiver.close()
            self.client.close()
            self.logger.info('Closed the connection.\n')

    def _send_error(self, message):
        self.sender.send(b'error ' + message.encode())

    @staticmethod
    def _get_command(line: bytes) -> Tuple[bytes, bytes]:
        sp = line.index(b' ')
        command = line[:sp]
        arg = line[sp + 1:]
        return command, arg
Ejemplo n.º 8
0
def main():
    args = _arg_parser_factory().parse_args()

    host = args.host
    port = args.port

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, port))

    logger = ConsoleLogger()
    coder = Base85Coder()
    reader = TCPReader(sock, coder)
    sender = TCPSender(sock, coder)

    logger.info('Connected to chat server...')

    file = show_messages()
    msg_receiver = ThreadingMessageReceiver(file, reader)
    msg_receiver.start()

    closed = False

    while not closed and not sock.__getattribute__('_closed'):
        try:
            data = input('>> ')
            if data.startswith('/'):
                data = data[1:]

                if data == 'login':
                    command = _login()
                elif data == 'register':
                    command = _register()
                elif data == 'logout':
                    command = _logout()
                elif data == 'create':
                    command = _create()
                elif data == 'join':
                    command = _join()
                elif data == 'leave':
                    command = _leave()
                elif data == 'close':
                    command = _close()
                else:
                    logger.error('unknown command.')
                    raise Exception()
                msg_receiver.command(data)
            else:
                command = _message(data)
                msg_receiver.message(data)
                msg_receiver.command('message')

            invoker = CommandInvoker()
            invoker.store_command(command)

            request = invoker.serialize().encode()
            sender.send(request)
            if isinstance(command, Close):
                sock.close()

        except Exception as e:
            if str(e) != '':
                print(str(e))
                exit()
Ejemplo n.º 9
0
 def get_reader(self) -> Reader:
     client, _ = self.sock.accept()
     self.sender = TCPSender(client, self.coder)
     return TCPReader(client, self.coder)