IO模型
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IO模型相关的知识,希望对你有一定的参考价值。
from socket import * import time s = socket() s.bind((\'127.0.0.1\',8080)) s.listen(5) s.setblocking(False) r_list=[] w_list=[] while True: try: conn, addr = s.accept() r_list.append(conn) except BlockingIOError: # time.sleep(0.05) print(\'可以去干其他的活了\') print(\'rlist: \',len(r_list)) # 收消息 del_rlist=[] for conn in r_list: try: data=conn.recv(1024) if not data: conn.close() del_rlist.append(conn) continue # conn.send(data.upper()) w_list.append((conn,data.upper())) except BlockingIOError: continue except ConnectionResetError: conn.close() # r_list.remove(conn) del_rlist.append(conn) # 发消息 del_wlist=[] for item in w_list: try: conn=item[0] res=item[1] conn.send(res) del_wlist.append(item) except BlockingIOError: continue except ConnectionResetError: conn.close() del_wlist.append(item) # 回收无用连接 for conn in del_rlist: r_list.remove(conn) for item in del_wlist: w_list.remove(item)
服务端
from socket import * import os client = socket() client.connect((\'127.0.0.1\', 8080)) while True: data=\'%s say hello\' %os.getpid() client.send(data.encode(\'utf-8\')) res=client.recv(1024) print(res.decode(\'utf-8\'))
from socket import * import select s=socket() s.bind((\'127.0.0.1\',8080)) s.listen(5) s.setblocking(False) r_list=[s,] w_list=[] w_data={} while True: print(\'被检测r_list: \',len(r_list)) print(\'被检测w_list: \',len(w_list)) rl,wl,xl=select.select(r_list,w_list,[],) for r in rl: if r==s: conn,addr=r.accept() r_list.append(conn) else: try: data=r.recv(1024) if not data: r.close() r_list.remove(r) continue w_list.append(r) w_data[r]=data.upper() except ConnectionRefusedError: r.close() r_list.remove(r) continue for w in wl: w.send(w_data[w]) w_list.remove(w) w_data.pop(w)
服务端
from socket import * import os client=socket() client.connect((\'127.0.0.1\',8080)) while True: data=\'%s say hello\'%os.getpid() client.send(data.encode(\'utf-8\')) res=client.recv(1024) print(res.decode(\'utf-8\'))
from concurrent.futures import ThreadPoolExecutor from threading import current_thread import time import os def task(n): print(\'%s is running\'%current_thread().name) time.sleep(2) return n**2 def parse(obj): res=obj.result() print(res) if __name__ == \'__main__\': t=ThreadPoolExecutor(3) future1=t.submit(task,1) future1.add_done_callback(parse) future2 = t.submit(task,2) future2.add_done_callback(parse) future3 = t.submit(task, 3) future3.add_done_callback(parse)
以上是关于IO模型的主要内容,如果未能解决你的问题,请参考以下文章
稳定性 耗时 监控原因分析-- dubbo rpc 框架 的线程池,io 连接模型. 客户端,服务端
csharp C#代码片段 - 使类成为Singleton模式。 (C#4.0+)https://heiswayi.github.io/2016/simple-singleton-pattern-us
使用片段时 Intellij 无法正确识别 Thymeleaf 模型变量