IO模型
程序员文章站
2024-01-16 10:59:28
解决问题是:服务端,网络IO 知识点回顾 from threading import Thread from socket import * def talk(conn): while True: try: data = conn.recv(1024) if not data: break conn ......
解决问题是:服务端,网络IO
知识点回顾
from threading import Thread from socket import * def talk(conn): while True: try: data = conn.recv(1024) if not data: break conn.send(data.uuper()) except ConnectionResetError: break conn.close() server = socket() # 默认TCP server.bind(('127.0.0.1', 8080)) server.listen(5) # 链接 while True: conn, addr = server.accept() print(addr) # 通信 t = Thread(target=talk,args=(conn,)) t.start() server.close() # 复习 from gevent import monkey,spawn;monkey.patch_all() import time def f1(): print('from f1 1') time.sleep(3) print('from f1 2') def f2(): print('from f2 1') time.sleep(2) print('from f2 2') def f3(): print('from f3 1') time.sleep(5) print('from f3 2') g1=spawn(f1) g2=spawn(f2) g3=spawn(f3) # 让主线程等任务执行完 g1.join() g2.join() g3.join() from gevent import monkey,spawn;monkey.patch_all() from socket import * def talk(conn): while True: try: data = conn.recv(1024) if not data: break conn.send(data.upper()) except ConnectionResetError: break conn.close() def server(ip,port,backlog=5): s = socket() # 默认TCP s.bind((ip, port)) s.listen(backlog) # 链接 while True: conn, addr = s.accept() print(addr) # 通信 g = spawn(talk,conn) # g.join() # 因为通信里有IO,主线程不需要另外等待的任务 server.close() if __name__ == '__main__': server('127.0.0.1',8080)
上一篇: C# 插件热插拔