"""
This is a RPC server/client implementation using socket
* It authenticate the client with a secret shared by client/server
* It uses JSON to serialize the function call payload
"""
import socket
import random, string
import hmac
import json
import threading
secret = "SECRET"
class RPCHandler:
def __init__(self, secret):
self._secret = secret
self._register = {}
def register_func(self, func):
self._register[func.__name__] = func
def handle_call(self, sock):
keymsg = ''.join([random.choice(string.lowercase) for i in range(8)])
sock.sendall(keymsg)
hash = hmac.new(self._secret, keymsg)
digest = hash.digest()
response = sock.recv(512)
if response != digest:
sock.sendall("Authentication Failed!")
sock.close()
else:
sock.sendall("Authenticated!")
try:
while True:
req = sock.recv(512)
d = json.loads(req)
funcname = d["name"]
args = d["args"]
kwargs = d["kwargs"]
print("Client calling %s(%s, %s)" % (funcname, args, kwargs))
try:
ret = self._register[funcname](*args, **kwargs)
sock.sendall(json.dumps({"ret": ret}))
except Exception as e:
sock.sendall(json.dumps({"exception": str(e)}))
except EOFError:
print("Closing RPC Handler...")
handler = RPCHandler(secret)
class RPCServer:
def __init__(self, address):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.bind(address)
def serve_forever(self):
self._sock.listen(0)
while True:
client_sock,_ = self._sock.accept()
thread = threading.Thread(target=handler.handle_call, args=(client_sock, ))
thread.daemon = True
thread.start()
class RPCProxy(object):
def __init__(self, address, secret):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.connect(address)
msg = self._sock.recv(512)
h = hmac.new(secret, msg)
self._sock.sendall(h.digest())
print(self._sock.recv(512))
def __getattr__(self, name):
def proxy_func(*args, **kwargs):
payload = {
"name": name,
"args": args,
"kwargs": kwargs
}
self._sock.sendall(json.dumps(payload))
result = json.loads(self._sock.recv(512))
if "exception" in result:
raise Exception(result['exception'])
else:
return result['ret']
if name.startswith("_"):
return super(RPCProxy, self).__getattr__(name)
else:
return proxy_func
【python-网络通信】这是一个用socket实现的简单的python RPC服务器/客户端。* 通过客户端/服务器共用的密码认证客户端* 使用JSON序列化函数调用有效负载
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 一. TCP服务器的实现 1.创建套接字 2.绑定本地终节点 3.开启监听 4.异步接收客户端连接请求 5.异步接...
- 就一个不用 理解之间的通信代码原理之类的 几句代码快速搭建服务器和客户端 思维导图: 过程大概是KGSocke...
- 接着上篇继续讲 1.KGNetSession socket的会话管理 就是管理接收/发送 数据消息的 这里流程是...
- 服务器端 server #!/usr/bin/env python # _*_ coding:utf-8 _*_ ...