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
|
import sys
import socket
from struct import pack, unpack
sys.path += ['..']
from pysearpc import SearpcClient, searpc_func
SERVER_ADDR = '127.0.0.1'
SERVER_PORT = 12345
def recv_all(sock, length):
"""
read all n bytes of data from sock
"""
data = ''
while len(data) < length:
more = sock.recv(length - len(data))
if not more:
raise EOFError('socket closed %d bytes into a %d-byte message' % (len(data), length))
data += more
return data
class SampleRpcClient(SearpcClient):
def call_remote_func_sync(self, fcall_str):
"""
called by searpc_func to send the request and receive the result
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# connect to server
s.connect((SERVER_ADDR, SERVER_PORT))
# send the header
header = pack('!h', len(fcall_str));
s.sendall(header)
# send the JSON data
s.sendall(fcall_str)
# read the returned header
header_r = recv_all(s, 2)
#read the result
ret_len = list(unpack('!h', header_r))[0]
if ret_len <= 0:
raise AssertionError, "returned data length <= 0"
ret_str = recv_all(s, ret_len)
return ret_str
@searpc_func("int", ["string"])
def searpc_strlen(self):
pass
client = SampleRpcClient()
res = client.searpc_strlen("hello world")
print 'result from server:', res
|