-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstress_test.py
112 lines (86 loc) · 3.53 KB
/
stress_test.py
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import socket
import time
class ClientError(Exception):
"""Общий класс исключений клиента"""
pass
class ClientSocketError(ClientError):
"""Исключение, выбрасываемое клиентом при сетевой ошибке"""
pass
class ClientProtocolError(ClientError):
"""Исключение, выбрасываемое клиентом при ошибке протокола"""
pass
class Client:
def __init__(self, host, port, timeout=None):
# класс инкапсулирует создание сокета
# создаем клиентский сокет, запоминаем объект socke.socket в self
self.host = host
self.port = port
try:
self.connection = socket.create_connection((host, port), timeout)
except socket.error as err:
raise ClientSocketError("error create connection", err)
def _read(self):
"""Метод для чтения ответа сервера"""
data = b""
# накапливаем буфер, пока не встретим "\n\n" в конце команды
while not data.endswith(b"\n\n"):
try:
data += self.connection.recv(1024)
except socket.error as err:
raise ClientSocketError("error recv data", err)
# не забываем преобразовывать байты в объекты str для дальнейшей работы
decoded_data = data.decode()
status, payload = decoded_data.split("\n", 1)
payload = payload.strip()
# если получили ошибку - бросаем исключение ClientError
if status == "error":
raise ClientProtocolError(payload)
return payload
def put(self, key, value, timestamp=None):
timestamp = timestamp or int(time.time())
# отправляем запрос команды put
try:
self.connection.sendall(
f"put {key} {value} {timestamp}\n".encode()
)
except socket.error as err:
raise ClientSocketError("error send data", err)
# разбираем ответ
self._read()
def get(self, key):
# формируем и отправляем запрос команды get
try:
self.connection.sendall(
f"get {key}\n".encode()
)
except socket.error as err:
raise ClientSocketError("error send data", err)
# читаем ответ
payload = self._read()
data = {}
if payload == "":
return data
# разбираем ответ для команды get
for row in payload.split("\n"):
key, value, timestamp = row.split()
if key not in data:
data[key] = []
data[key].append((int(timestamp), float(value)))
return data
def close(self):
try:
self.connection.close()
except socket.error as err:
raise ClientSocketError("error close connection", err)
def _main():
# проверка работы клиента
clients = []
for i in range(0,1000000000):
print(i)
client = Client("192.168.31.99", 8888)
#client.put("test", 0.5, timestamp=1)
clients.append(client)
for i in range(0, 1000000000):
clients[i].put("test", 0.5, timestamp=1)
if __name__ == "__main__":
_main()