协程实现tcp两个客户端的通讯
import socket import gevent from gevent import monkey monkey.patch_all() def cb_work(recv_num,send_num): while True: recv_data=list_client[recv_num][0].recv(1024).decode("gbk") if recv_data: list_client[send_num][0].send(recv_data.encode("gbk")) else: break list_client[recv_num][0].close() if __name__=="__main__": #创建套接字 tcp_server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #端口复用 tcp_server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True) #绑定地址 tcp_server_socket.bind(("",8080)) #监听 tcp_server_socket.listen(128) #等待 list_client=[] list_gevent=[] for i in range(2): list_client.append(tcp_server_socket.accept()) if i==1: list_gevent.append(gevent.spawn(cb_work,*(i,0))) else: list_gevent.append(gevent.spawn(cb_work,*(i,1))) gevent.joinall(list_gevent) tcp_server_socket.close()