summaryrefslogtreecommitdiff
path: root/tester.py
blob: 26d694e93c4aa7afe86f13d0cb5539614f16b4ea (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
from socket import socket
import json
from time import sleep, time


MESSAGE, AUTHENTICATE, RENAME = "message", "authenticate", "rename"


def int_from_bytes(data: bytes) -> int:
    num = 0
    for i, byte in enumerate(data):
        num += byte << ((4 - i - 1) * 8)
    return num


def to_bytes(num: int) -> bytes:
    b = bytearray(4)
    mask = 0xFF
    for i in range(4):
        b[4 - i - 1] = num & mask
        num >>= 8
    return bytes(b)


def send_message(connection: socket, data: bytes):
    size = len(data)
    b = to_bytes(size)
    # print(size, list(map(int, b)))
    connection.sendall(b + data)


def main():
    with socket() as sock:
        addr = host, port = "localhost", 8080
        print(addr)
        sock.connect(addr)

        t1 = time()

        request = {
            "type": AUTHENTICATE,
            "data": "auth",
            "user": "andrew"
        }
        send_message(sock, json.dumps(request).encode())

        response = sock.recv(4)
        size = int_from_bytes(response)
        response = sock.recv(size).decode()
        print(f"Response: {response}")

        for i in range(10000):
            print(f"Sending {i} request")
            # msg = input("Enter message: ")
            request = {
                "type": MESSAGE,
                "data": f"hello, {i}",
                # "data": msg,
                "user": "andrew"
            }
            send_message(sock, json.dumps(request).encode())

            print("Waiting for response")
            response = sock.recv(4)
            size = int_from_bytes(response)
            # print(f"Size is {size}")

            response = sock.recv(size).decode()
            print(f"Response: {response}")

        request = {
            "type": MESSAGE,
            "data": "exit",
            "user": "andrew"
        }
        send_message(sock, json.dumps(request).encode())
        print(time() - t1)


if __name__ == '__main__':
    main()