30
30
31
31
32
32
class BridgeClient :
33
+ def __init__ (self ):
34
+ self .json = None
35
+ self .should_close_at_function_end = True
36
+
33
37
def wait_response (self , json , timeout ):
34
38
while timeout >= 0 :
35
39
r = json .recv ()
@@ -50,39 +54,57 @@ def wait_key(self, key, json, timeout):
50
54
except :
51
55
pass
52
56
57
+ def socket_open (self ):
58
+ if self .json is None :
59
+ self .json = TCPJSONClient ('127.0.0.1' , 5700 )
60
+ return self .json
61
+
62
+ def socket_close (self ):
63
+ if self .json is not None and self .should_close_at_function_end :
64
+ self .json .close ()
65
+ self .json = None
66
+
67
+ def begin (self ):
68
+ self .socket_open ()
69
+ self .should_close_at_function_end = False
70
+
71
+ def close (self ):
72
+ self .should_close_at_function_end = True
73
+ self .socket_close ()
74
+
53
75
def get (self , key ):
54
- json = TCPJSONClient ( '127.0.0.1' , 5700 )
76
+ json = self . socket_open ( )
55
77
json .send ({'command' : 'get' , 'key' : key })
56
78
r = self .wait_key (key , json , 10 )
57
- json . close ()
79
+ self . socket_close ()
58
80
return r
59
81
60
82
def getall (self ):
61
- json = TCPJSONClient ( '127.0.0.1' , 5700 )
83
+ json = self . socket_open ( )
62
84
json .send ({'command' : 'get' })
63
85
r = self .wait_response (json , 10 )
64
86
if not r is None :
65
87
r = r ['value' ]
66
- json . close ()
88
+ self . socket_close ()
67
89
return r
68
90
69
91
def put (self , key , value ):
70
- json = TCPJSONClient ( '127.0.0.1' , 5700 )
92
+ json = self . socket_open ( )
71
93
json .send ({'command' : 'put' , 'key' : key , 'value' : value })
72
94
r = self .wait_key (key , json , 10 )
73
- json . close ()
95
+ self . socket_close ()
74
96
return r
75
97
76
98
def delete (self , key ):
77
- json = TCPJSONClient ( '127.0.0.1' , 5700 )
99
+ json = self . socket_open ( )
78
100
json .send ({'command' : 'delete' , 'key' : key })
79
101
r = self .wait_response (json , 10 )
80
102
if not r is None and not r ['value' ] is None :
81
103
r = r ['value' ]
82
- json . close ()
104
+ self . socket_close ()
83
105
return r
84
106
85
107
def mailbox (self , message ):
86
- json = TCPJSONClient ( '127.0.0.1' , 5700 )
108
+ json = self . socket_open ( )
87
109
json .send ({'command' : 'raw' , 'data' : message })
88
- json . close ()
110
+ self . socket_close ()
0 commit comments