summaryrefslogtreecommitdiff
path: root/day4/task3/client.py
blob: 18bb2b107caef1f7f069bbec1d24e5883c8c1f1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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()