1. 程式人生 > >socketserver實現多執行緒演算法請求伺服器

socketserver實現多執行緒演算法請求伺服器

需要實現客戶端發來的演算法執行請求,寫了一個多執行緒的響應框架,能夠實現響應多個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()