RODY/app/services/RpcClient2.py
552068321@qq.com 6f7de660aa first commit
2022-11-04 17:37:08 +08:00

56 lines
1.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
@Time 2022/9/30 17:09
@Auth
@File RpcClient.py
@IDE PyCharm
@MottoABC(Always Be Coding)
@DescRPC客户端
"""
import json
import socket
import time
class TCPClient(object):
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self, host, port):
"""链接Server端"""
self.sock.connect((host, port))
def send(self, data):
"""将数据发送到Server端"""
self.sock.send(data)
def recv(self, length):
"""接受Server端回传的数据"""
return self.sock.recv(length)
class RPCStub(object):
def __getattr__(self, function):
def _func(*args, **kwargs):
d = {'method_name': function, 'method_args': args, 'method_kwargs': kwargs}
self.send(json.dumps(d).encode('utf-8')) # 发送数据
data = self.recv(1024) # 接收方法执行后返回的结果
return data.decode('utf-8')
setattr(self, function, _func)
return _func
class RPCClient(TCPClient, RPCStub):
pass
# c = RPCClient()
# c.connect('127.0.0.1', 5003)
# print(c.start('1'))
# print(c.add(1, 2, 3))
# print(c.setData({"sss": "ssss", "list": [1, 2, 3, 4]}))