socket.connect()
。当我尝试这样做时,该方法总是抛出一个BlockingIOError
。当我忽略错误(如下所示)时,程序按预期执行。当我在连接之后将套接字设置为非阻塞时,就不会出现错误。当我使用select.select()来确保套接字可读或可写时,仍然会出现错误。
testserver.py
import socket
import select
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(0)
host = socket.gethostname()
port = 1234
sock.bind((host, port))
sock.listen(5)
while True:
select.select([sock], [], [])
con, addr = sock.accept()
message = con.recv(1024).decode('UTF-8')
print(message)
testclient.py
import socket
import select
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(0)
host = socket.gethostname()
port = 1234
try:
sock.connect((host, port))
except BlockingIOError as e:
print("BlockingIOError")
msg = "--> From the client\n"
select.select([], [sock], [])
if sock.send(bytes(msg, 'UTF-8')) == len(msg):
print("sent ", repr(msg), " successfully.")
sock.close()
终端 1
$ python testserver.py
--> From the client
终端 2
$ python testclient.py
BlockingIOError
sent '--> From the client\n' successfully.
这段代码正确运行,除了第一个connect()出现的BlockingIOError。该错误的文档解释如下:当一个对象(例如套接字)被设置为非阻塞操作时,如果一个操作将会被阻塞,则会引发此错误。
我该如何使用设置为非阻塞的套接字进行正确的connect()连接?我能使connect()变为非阻塞吗?还是直接忽略这个错误比较合适?