标签:get lse .so else from for 参数 code tin
select必须传入三个参数分别是三个列表read_list, write_list, erro_list返回值是一个元祖对应传入的参数
#select帮助感知某个IO操作是否有变动
#read开始被read
#write开始被write
#erro开始有erro
#一但感知到就会返回响应的参数
import socket
from select import select
sk = socket.socket()
address = (‘127.0.0.1‘, 8080)
sk.bind(address)
sk.setblocking(False)
sk.listen() #监听
read_ls = [sk] #将sk对象加入一个列表
while 1:
r_ls, w_ls, x_ls = select(read_ls, [], [])
for i in r_ls:
if i is sk:
conn, addr = i.accept()
read_ls.append(conn)
else:
ret = i.recv(1024) #接收消息
if ret == b‘‘:
read_ls.remove(i)
i.close()
continue
print(ret)
i.send(b‘byebye!‘) #发送消息
客户端 -起多线程的客户端
import socket
from threading import Thread
def func():
sk = socket.socket()
address = (‘127.0.0.1‘, 8080)
sk.connect(address)
sk.send(b‘hello‘)
ret = sk.recv(1024)
print(ret)
sk.close()
t_ls = []
for i in range(10):
t = Thread(target=func)
t.start()
select
机制基本上一样poll
监听的对象比select
监听上限多标签:get lse .so else from for 参数 code tin
原文地址:https://www.cnblogs.com/liliudong/p/9746912.html