socket+select伪并发
s1
import socket
import select
sk1 = socket.socket()
sk1.bind(("127.0.0.1",8001))
sk1.listen()
sk2 = socket.socket()
sk2.bind(("127.0.0.1",8002))
sk2.listen()
inputs = [sk1,sk2]
outputs = []
message_dict = {}
while True:
#select内部自动监听sk1,sk2,对象,一旦某一个句柄发生变化
#r_list = [sk1,sk2]
r_list,w_list,e_list = select.select(inputs,outputs,inputs,1)#最大等待1秒
# 发生变化的 有什么给什么 错误的 最多监听1024个 poll对个数没限制了 底层都是for循环
# epoll,谁发生变化了告诉一下,不是for循环,异步。Nginx基于socket和epoll
print("正在监听 %s 个" % len(inputs))
for sk_or_conn in r_list:
# conn,adress = sk.accept()
# conn.sendall(bytes("hello",encoding="utf-8"))
# conn.close()
if sk_or_conn == sk1:
#有新用户加入了
conn,adress = sk_or_conn.accept()
inputs.append(conn)
message_dict[conn] = []
else:
#有老用户发消息了
try:
data_bytes = sk_or_conn.recv(1024)
# ret = str(data_bytes,encoding="utf-8")
# sk_or_conn.sendall(bytes(ret+"好",encoding="utf-8"))
#else:#2.7如果c关闭,发送过来一个空字节,移除sk
except Exception as e:
inputs.remove(sk_or_conn)
else:
ret = str(data_bytes,encoding="utf-8")
message_dict[sk_or_conn].append(ret)
# sk_or_conn.sendall(bytes(ret+"好",encoding="utf-8"))
outputs.append(sk_or_conn)
for conn in w_list:
#仅保存了谁给我发过消息
recv_str = message_dict[conn][0]
del message_dict[conn][0]
conn.sendall(bytes(recv_str+"好",encoding="utf-8"))
outputs.remove(conn)
# 优化,queue队列,先进先出,不用del,发一个删一个
for sk in e_list:
inputs.remove(sk)
c1
import socket
sk = socket.socket()
sk.connect(("127.0.0.1",8001))
while True:
sk.sendall(bytes(input(">>>:"),encoding="utf-8"))
ret = str(sk.recv(1024),encoding="utf-8")
print(ret)
#梳理
#1.socket,服务端同时只能处理一个请求
#2.select +socket,伪并发。r_list即度又写。w_list读写分离
#3.socketserver select/epoll +socket +多线程,实现并发
#注意:类的继承