1. 程式人生 > >非阻塞socket與io多路複用(沒整理好)

非阻塞socket與io多路複用(沒整理好)

非阻塞套接字
多人聊天客戶端
import socket
server = socket.socket()
server.setblocking(False) #設定非阻塞
server.bind("",6969)
server.listen(5)
clients = [ ] 存放連線進來的客戶端
while True:
#迴圈接收客戶端
try:
conn,addr = server.accept()
conn.setblocking(False) #設定這個對等連線為非阻塞
clients.append((conn,addr))
except Exception:
pass
#迴圈處理對等連線
for client,addr in clients:
#收資料
try:
recv_data = client.recv(1024)
if recv_data:
#給所有的人發一份
data = “receive {} from {}”.format(
recv_data.decode(“utf-8”),
addr
)
for c,a in clients:
c.send(recv_data)
else:
clients.remove((client,addr))
client.close()
except Exception:
pass

#傳送端
import socket
client = socket.socket()
client.connect((“127.0.0.1”,6969))
while True:
data = input(">>>")
if data = “q”:
break
client.send(dta.encode)
client.close()

#接收端
import socket
client = socket.socket()
client.connect((“127.0.0.1”,6969))
while True:
res = client.recv(1024)
print(res.decode(“utf-8”))