select是一個io多路複用的io模型,也叫作事件驅動的io模型,咱們今天用select來實現一個多併發的socket的聊天的程序python
先看下server端的代碼併發
import socket import select socket_list = [] socket_list_all = [] def create_socket(): for i in range(9000,9100): socket_name = "socket_" + str(i) socket_name = socket.socket() addr = ("127.0.0.1",i) socket_name.bind(addr) socket_name.listen(10) socket_list.append(socket_name) #負責存放全部的socket服務端的對象 socket_list_all.append(socket_name) #負責存儲全部的socket服務端和客戶端的socket對象 #生成100個socket對象 socket_list_temp = socket_list if __name__ == '__main__': create_socket() while True: r,w,e = select.select(socket_list_all,[],[]) #監聽socket列表 for obj in r: if obj in socket_list: conn,addr = obj.accept() socket_list_all.append(conn) break #若是在socket_list,在說明是一個新的鏈接過來鏈接socketserver else: #若是不是,則說明是已有的鏈接 client_data = obj.recv(1024) print(obj, str(client_data, encoding="utf-8"), sep=">>>>") server_data = input("server:") obj.sendall(bytes(server_data, encoding="utf-8"))
在來看客戶端的代碼app
import socket ip_bind = ("127.0.0.1",9000) client1= socket.socket() client1.connect(ip_bind) while True: clent_data = input("client:") client1.sendall(bytes(clent_data,encoding="utf-8")) server_data = client1.recv(1024) print("server",str(server_data,encoding="utf-8"))