例子都是相对较基础的例子,但是能够支持的功能是实际存在的,不知道实际生产是否会用这样的方式呢
1、服务器端代码
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
import socket,sys import gevent,time from gevent import socket,monkey monkey.patch_all() def server(port): s = socket.socket() s.bind(('0.0.0.0',port)) s.listen(500) while True: cli,addr = s.accept() gevent.spawn(handle_request,cli) def handle_request(conn): try: while True: data = conn.recv(1024) print('recv data len',len(data)) if not data: conn.send(b'no data') continue; conn.send(data) except Exception as e: print(e) finally: conn.close() if __name__ == '__main__': server(8001)
2、客户端代码
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
import os,time,socket PORT = 8001 HOST = 'localhost' s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((HOST,PORT)) while True: msg = bytes(input(">>"),encoding ="utf-8") s.sendall(msg) data = s.recv(1024) print('recv from server',data) s.close()