博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 用socket搭建socket服务器-多线程网络编程
阅读量:3965 次
发布时间:2019-05-24

本文共 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/

你可能感兴趣的文章
P9-c++对象和类-02构造函数和析构函数总结
查看>>
P10-c++对象和类-03this指针详细介绍,详细的例子演示
查看>>
bat备份数据库
查看>>
linux数据库导出结果集且比对 && grep -v ---无法过滤的问题
查看>>
shell函数与自带变量
查看>>
linux下shell获取不到PID
查看>>
sort详解
查看>>
linux,shell中if else if的写法,if elif
查看>>
shell中单引号、双引号、反引号的区别
查看>>
shell脚本死循环方法
查看>>
shell中$*和$@的区别
查看>>
log4cxx 的编译安装过程和使用
查看>>
简单邮件系统程序
查看>>
STL里的multimap使用详解
查看>>
STL 库其中的 std::string用法总结
查看>>
模态对话框的销毁过程与非模态对话的几种销毁方法
查看>>
C++实现http下载 && 24点计算编码风格
查看>>
memcached了解使用和常用命令详解
查看>>
GDB调试各功能总结
查看>>
"undefined reference to" 多种可能出现的问题解决方法
查看>>