diff options
Diffstat (limited to 'day4/task3/client.py')
| -rw-r--r-- | day4/task3/client.py | 85 |
1 files changed, 85 insertions, 0 deletions
diff --git a/day4/task3/client.py b/day4/task3/client.py new file mode 100644 index 0000000..18bb2b1 --- /dev/null +++ b/day4/task3/client.py @@ -0,0 +1,85 @@ +import socket +from time import sleep +import struct +import json + + +HOST, PORT = ADDR = 'localhost', 6000 +DATATYPE_SIZE = 4 # int + + +def pack_data(data): + encoded = data.encode() + return struct.pack('I', len(encoded)) + encoded + + +def get_data(connection): + buffer = b'' + # Считываем размер пакета + while len(buffer) < DATATYPE_SIZE: + data = connection.recv(DATATYPE_SIZE - len(buffer)) + if not data: + raise ConnectionError('Connection was closed') + + buffer += data + + size_packed, buffer = buffer[:DATATYPE_SIZE], buffer[DATATYPE_SIZE:] + if not size_packed: + raise ConnectionError('Connection was closed') + + (size,) = struct.unpack('I', size_packed) + data = connection.recv(size - len(buffer)) + return buffer + data + + +def parse_data(data): + return json.loads(data.decode()) + + +def try_connect(): + cnt = 0 + sock = socket.socket() + while cnt < 10: + try: + cnt += 1 + sock.connect(ADDR) + + except ConnectionRefusedError: + print('Не удалось подключиться к серверу. Следующая попытка через 3 секунды...') + sleep(3) + + else: + return sock + + else: + print('Не удалось подключиться к серверу через 10 попыток.\nОстанавливаемся...') + sock.close() + return + + +def main(): + sock = try_connect() + if sock is None: + quit() + + while True: + try: + data = input('Введите модуль для поиска:\n') + + except KeyboardInterrupt: + break + + else: + sock.sendall(pack_data(data)) + response = get_data(sock) + arr = parse_data(response) + + print(f'Найдено {len(arr)} совпадений:') + for line in arr: + print(line) + + sock.close() + + +if __name__ == '__main__': + main() |