web-client.py
2.33 KB
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
import sys
import requests
import json
from datetime import datetime
from time import (
sleep,
time,
)
from threading import Thread
from optparse import OptionParser
threads = {}
end_threads = []
durations = {}
json_responses = {}
def create_thread(func, args=[]):
thread = Thread(target=func, args=args)
# Exit the server thread when the main thread terminates
thread.daemon = True
return thread
def send(p):
key = p['id']
log_info('Request: {}'.format(p))
start = time()
try:
resp = requests.post(url, data=json.dumps(p), headers=headers)
durations[key] = time() - start
json_resp = resp.json()
log_info('Response: {}'.format(json_resp))
json_responses[key] = json_resp
finally:
end_threads.append(key)
def log_info(s):
t = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
t = t[:-3]
msg = '{} {}'.format(t, s)
print(msg)
default_url = 'http://localhost:7000/rpc'
default_host = 'pemda'
default_count = 1
help_url = 'default ' + default_url
help_host = 'default ' + default_host
help_count = 'default {}'.format(default_count)
parser = OptionParser()
parser.add_option('', '--url', default=default_url, help=help_url)
parser.add_option('', '--host', default=default_host, help=help_host)
parser.add_option(
'-c', '--count', type='int', default=default_count, help=help_count)
option, args = parser.parse_args(sys.argv[1:])
url = option.url
count = option.count
headers = {'content-type': 'application/json'}
p = {'host': option.host}
data = {
'method': 'echo',
'params': [p],
'jsonrpc': '2.0',
}
for i in range(count):
data['id'] = i
thread = create_thread(send, [dict(data)])
threads[i] = thread
for key in threads:
thread = threads[key]
thread.start()
sleep(0.2)
while threads:
sleep(1)
if not end_threads:
continue
i = end_threads[0]
if i in threads:
thread = threads[i]
thread.join()
del threads[i]
index = end_threads.index(i)
del end_threads[index]
for key in durations:
val = durations[key]
resp = json_responses[key]
if 'error' in resp:
break
result = resp['result']
if result['code'] == 0:
stan = result['data']['11']
else:
stan = '-'
print('thread {} stan {} {} detik'.format(key, stan, val))