select实现ftp
import select
import socket
server = socket.socket()
server.bind((‘127.0.0.1‘, 9991))
server.listen(10)
server.setblocking(False)
r_list = [server, ]
w_list = []
w_data = {}
while True:
rl, wl, xl = select.select(r_list, w_list, [], 0.5)
print(wl)
for sock in rl:
if sock == server:
conn, addr = server.accept()
r_list.append(conn)
else:
try:
data = sock.recv(1024).decode()
if not data:
sock.close()
r_list.remove(sock)
continue
w_list.append(sock)
w_data[sock] = data.upper().encode()
except Exception as e:
print(e)
sock.close()
r_list.remove(sock)
selectors 实现ftp
import selectors
import socket
def accept(obj, mask):
conn,addr = obj.accept()
sel.register(conn, selectors.EVENT_READ, read)
def read(obj,mask):
try:
data = obj.recv(1024).decode()
if not data:
sel.unregister(obj)
obj.close()
return
print(data)
obj.send(data.upper().encode())
except Exception as e:
print(e)
obj.close()
sel.unregister(obj)
server = socket.socket()
server.bind((‘127.0.0.1‘, 9990))
server.listen(10)
server.setblocking(False)
sel = selectors.DefaultSelector()
sel.register(server, selectors.EVENT_READ, accept)
while True:
events = sel.select()
for obj, mask in events:
callback = obj.data
callback(obj.fileobj, mask)