非阻塞io模型
非阻塞io模型
#server端
import socket
sk = socket.socket()
sk.bind(("127.0.0.1",9000))
sk.setblocking(False) #将其设置为非阻塞模型,如果发生了阻塞便报错
sk.listen()
conn_1 = []
del_1 = []
while True:
try:
conn,addr = sk.accept() #阻塞,直到有一个客户端连我
# print(conn) #接受了一个便打印
conn_1.append(conn)
except BlockingIOError: #无接受时,便报错,没接受,便进入该循环
for c in conn_1: #将所接受的各个元素拿出来
try:
msg = c.recv(1024).decode("utf-8")
if not msg:
del_1.append(c)
print(msg)
c.send(msg.upper().encode("utf-8"))
except BlockingIOError:pass
for c in del_1:
conn_1.remove(c)
del_1.clear()
sk.close()
#socket的非阻塞io模型 + io多路复用实现的
#虽然非阻塞,提高了cpu的利用率,但是消耗了cpu做了很多无用功
#client1端
import socket
import time
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
for i in range(30):
sk.send(b"alex")
msg = sk.recv(1024)
print(msg)
time.sleep(0.2)
sk.close()
#client2端
import socket
import time
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
for i in range(30):
sk.send(b"wusir")
msg = sk.recv(1024)
print(msg)
time.sleep(0.2)
sk.close()
记录学习的点点滴滴