我正在学习selectors
模块,并且在断开与服务器的连接后不知道如何重新连接。
代码
import selectors
import socket
import time
import traceback
sel = selectors.DefaultSelector()
server_addr = ("localhost", 9978)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(server_addr)
sock.setblocking(False)
def handle(sock: socket.socket, mask):
try:
if mask & selectors.EVENT_WRITE:
time.sleep(1)
sock.send(b'hello')
if mask & selectors.EVENT_READ:
data = sock.recv(1024)
print('recv', data)
except socket.error:
traceback.print_exc()
# sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect(server_addr)
except socket.error:
traceback.print_exc()
sel.register(sock, selectors.EVENT_WRITE| selectors.EVENT_READ, handle)
while True:
for key, mask in sel.select(): #type:selectors.SelectorKey
callback = key.data
callback(key.fileobj, mask)
如果创建新的套接字以重新连接,则必须在选择器中注册它。有什么办法可以正常处理吗?