需要实现客户端发来的算法执行请求,写了一个多线程的响应框架,能够实现响应多个IP的请求,并且不受客户端断开的影响。
服务器端
import socketserver
import json
class Algrithom(object):
def __init__(self,name):
self.name = name
def calc_sub(self,*args):
para_inside=args
print(type(para_inside))
print("%s is running calc_sub,and para is %s"%(self.name,para_inside))
def calc_undefine():
print("This function is undefined....")
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
a = Algrithom("AIwater")
count=0
while True:
try:
self.data =self.request.recv(1024).strip()
msg_dic = json.loads(self.data.decode())
print("{} wrote:".format(self.client_address[0]))
# with open('D:/server.log', 'w') as f:
# f.write(self.client_address[0])
print(msg_dic)
function=msg_dic["function"]
para=msg_dic["para"]
if hasattr(a,function):
func=getattr(a,function)
func(para)
self.request.send("Algrithom finish".encode('utf-8'))
else:
setattr(a,function,calc_undefine)
func = getattr(a, function)
func()
self.request.send("Function is undefined".encode('utf-8'))
count+=1
if count >10:break
except ConnectionResetError as e:
print("err",e)
break
if __name__ == "__main__":
HOST, PORT = "localhost", 6969
# Create the server, binding to localhost on port 6969
server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)
server.allow_reuse_address
server.serve_forever()
测试用客户端
import socket
import json
client = socket.socket() #声明socket类型,同时生成socket连接对象
client.connect(('localhost',6969))
client.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
while True:
function = input("Please input function:").strip()
para = input("Please input para:").strip()
msg_dic={"function":function,
"para":para}
if len(function) == 0:continue
client.send(json.dumps(msg_dic).encode("utf-8"))
data = client.recv(1024)
print("recv:",data.decode())
client.close()