协程-基于TCP的高并发通信
from gevent import monkey;monkey.patch_all() from socket import * import gevent def sever(ipport): s = socket(AF_INET,SOCK_STREAM) s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) s.bind(ipport) s.listen(5) while True: cnn, addr = s.accept() print('%s is from %s'%(cnn, addr)) gevent.spawn(talk, cnn,addr) s.close() def talk(cnn,addr): while True: try: res = cnn.recv(1024).decode('utf-8') cnn.send(res.upper().encode('utf-8')) except Exception:break cnn.close() if __name__ == '__main__': ipport = ('127.0.0.1', 8080,) sever(ipport)
from socket import * from threading import Thread def client(ipport): c = socket(AF_INET,SOCK_STREAM) c.connect(ipport) while True: try: # res = input('>>').strip() # if not res:continue res = 'hello' c.send(res.encode('utf-8')) ree = c.recv(1024).decode('utf-8') print(ree) except Exception:break c.close() if __name__ == '__main__': ipport = ('127.0.0.1',8080,) for i in range(500): t = Thread(target=client,args=(ipport,)) t.start()
由于协程的作用及其轻量化,使高并发(看起来是高并发)实现起来简单快捷,至少我的电脑(8核核多了也没用,只有一个线程,10000个核也只能用一个核运行)能开1024个线程去访问服务端开的协程(客户端之所以不用协程实验是因为看不出效果,感觉跟串行似的)