程序代码:
import os,sys
from select import select
from socket import *
"""
通过select,监听套接字实例
"""
ADDR = ('0.0.0.0',8888)
s = socket()
s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
s.bind(ADDR)
s.listen(3)
#设置监听列表
rlist = [s]
wlist = []
xlist = []
#开始监听
while True:
rs,ws,xs = select(rlist,wlist,xlist)
#遍历返回值列表,处理就绪的IO
for r in rs:
if r is s: # 连接套接字就绪
c,addr = r.accept()
print(addr)
rlist.append(c) # 把收消息套接字加入到监听读列表
else: # 客户端消息就绪
data = r.recv(1024).decode()
if not data:
rlist.remove(r)
r.close()
continue
print(data)
# r.send(b'OK')
wlist.append(r) # 把发消息套接字加入到监听读列表
for w in ws:
w.send(b'OK') # 通过监听wlist主动给客户端回复信息
wlist.remove(w)
for x in xs:
pass
[此贴子已经被作者于2023-4-28 07:25编辑过]