-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
103 lines (77 loc) · 2.92 KB
/
client.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
from __future__ import print_function
import requests
import json
from gevent.threadpool import ThreadPool
import functools
import time
import random
class Worker(object):
def __init__(self, url):
self.url = url
self.headers = {'content-type': 'application/json'}
self.id = 0
self.post = functools.partial(requests.post, self.url, headers=self.headers)
self.pool = ThreadPool(100)
def _call(self, method, *args):
payload = dict(method=method, params=args, jsonrpc="2.0", id=self.id)
self.id += 1
response = self.post(json.dumps(payload)).json()
return response
def _async_call(self, method, *args):
payload = dict(method=method, params=args, jsonrpc="2.0", id=self.id)
self.id += 1
def _delayed_call(pl):
return self.post(json.dumps(pl)).json()
return Future(self.pool.spawn(_delayed_call, payload))
def tell(self, method, *args):
self._async_call(method, *args)
def ask(self, method, *args):
return self._async_call(method, *args)
def join(self):
self.pool.join()
class Future:
def __init__(self, result):
self.result = result
self.true_result = None
def __repr__(self):
return str(self.get())
def get(self):
return self.true_result or self.result.get().get('result', self.result.get().get('error'))
def complete(self):
return self.result.ready()
def on_complete(self, func):
def _func(arg):
self.true_result = arg.get().get('result', arg.get().get('error'))
func(self.true_result)
self.result.rawlink(_func)
return self
if __name__ == "__main__":
worker = Worker('http://127.0.0.1:8080/rpc')
def blocking():
print("** blocking **")
stime = time.clock()
print(worker.ask("power", 2, 6).get())
print(worker.ask("echo", "echome!").get())
print(time.clock() - stime)
def non_blocking():
print("** non-blocking **")
stime = time.clock()
worker.tell("power", random.randint(0, 10), random.randint(0, 10))
worker.tell("echo", "echome!")
print("elapsed time: (tell message): {}".format(time.clock() - stime))
stime = time.clock()
r1 = worker.ask("power", random.randint(0, 10), random.randint(0, 10)).on_complete(print)
r2 = worker.ask("echo", "echome!").on_complete(print)
ttime = time.clock() - stime
print("elapsed time (send messages): {}".format(time.clock() - stime))
print("do other jobs")
time.sleep(15)
stime = time.clock()
print("get", r1.get())
print("get", r2.get())
ttime += time.clock() - stime
print("elapsed time (get respond): {}".format(time.clock() - stime))
print("total elapsed time: {}".format(ttime))
blocking()
print()
non_blocking()