rpc服务器【单线程同步】模型

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
client.py 客户端代码
# -*- coding: UTF-8 -*-
import json
import struct
import socket
import time


def rpc(sock, in_, params):
request = json.dumps({"in": in_, "params": params}) # 请求消息体
# print(request)
length_prefix = struct.pack("I", len(request)) # 请求长度前缀
# print(length_prefix)
# request2 = struct.pack("c", request)
# print(request2)
sock.sendall(length_prefix)
sock.sendall(request.encode())
length_prefix = sock.recv(4) # 响应长度前缀
# print(length_prefix)
length, = struct.unpack("I", length_prefix)
body = sock.recv(length) # 响应消息体
response = json.loads(body)
return response["out"], response["result"] # 返回响应类型和结果...


if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 8080))
for i in range(10):
out, result = rpc(s, "ping", "ireader %d" % i)
print(out, result)
time.sleep(1)
s.close()
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
# -*- coding: UTF-8 -*-

import json
import struct
import socket
import time


def loop(s, handlers):
while True:
conn, addr = s.accept()
handle_conn(conn, addr, handlers) # 处理连接


def handle_conn(conn, addr, handlers):
print(addr, "comes")
while True: # 循环读写
length_prefix = conn.recv(4) # 请求长度前缀
if not length_prefix: # 连接关闭了
print
addr, "bye"
conn.close()
break # 退出循环,处理下一个连接
length, = struct.unpack("I", length_prefix)
body = conn.recv(length).decode() # 请求消息体
request = json.loads(body)
in_ = request['in']
params = request['params']
print( in_, params)
handler = handlers[in_] # 查找请求处理器
handler(conn, params) # 处理请求...


def send_result(conn, out, result):
response = json.dumps({"out": out, "result": result}) # 响应消息体
length_prefix = struct.pack("I", len(response)) # 响应长度前缀
conn.sendall(length_prefix)
conn.sendall(response.encode())


def ping(conn, params):
send_result(conn, "pong", params)


if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 打开 reuse addr 选项
s.bind(("localhost", 8080))
s.listen(1)
handlers = {
"ping": ping
}
loop(s, handlers)