本文共 2804 字,大约阅读时间需要 9 分钟。
#ThreadSocket.pyimport socketimport threadingimport parserclass ThreadSocket(object): """ """ todo_list = { 'task_01': 'see someone', 'task_02': 'read book', 'task_03': 'play basketball', } def __init__(self, host, port): self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) def listen(self): self.sock.listen(5) while True: client, address = self.sock.accept() client.settimeout(60) local = threading.local() threading.Thread(target=self.handleClientRequest, args=(client,address,local)).start() def handleClientRequest(self, client, address,local): local.todo_list = { } while True: try: data = client.recv(1024) if data: response = parser.ClientRequestParser(data=data,db=local.todo_list).response() client.send(response) else: raise socket.error("Client has disconnected") except: client.close()if __name__ == '__main__': server = ThreadSocket('', 9000) server.listen()
import reclass ClientRequestParser: def __init__(self,data,db): try: pattern = re.compile(r'(?P.*)/(?P .*)/(?P .*)') m = pattern.match(data) self.request_data = m.groupdict() self.request_method = self.request_data.get('method','No key Found') self.db = db except: print('client command error') self.request_method = 'no method' def get(self,db,task_id): response = db.get(task_id,'key Not Found') return response def post(self,db,command): pattern = re.compile(r'(?P .*)=(?P .*)') m = pattern.match(command) post_data = m.groupdict() key = post_data.get('key','Key Not Found') value = post_data.get('value','Value Not Found') db[key]=value response = 'submit success' return response def response(self): response = '' if self.request_method == 'GET': print('GET method') task_id = self.request_data.get('command','No Key Found') response = self.get(self.db,task_id) elif self.request_method == 'POST': print('GET method') command = self.request_data.get('command', 'No Key Found') response = self.get(self.db, command) else: response = 'client reqy=uest error' response = response + '\r\n' return response
打开客户端
nc 127.0.0.1 9000
转载地址:http://hqezi.baihongyu.com/