在Python中,我想在我設置爲非阻塞的套接字上使用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.
此代碼正常除了BlockingIOError在第一連接()。錯誤的文檔如下所示:Raised when an operation would block on an object (e.g. socket) set for non-blocking operation.
如何正確連接()與套接字設置爲非阻塞?我可以使connect()非阻塞嗎?或者忽略錯誤是否合適?
此鏈接可能會對您有所幫助: http://stackoverflow.com/questions/1205863/how-can-i-get-non-blocking-socket-connects – akash12300
@ Akash1993是的,當我以前看過那個問題時很難將它與我簡單的例子聯繫起來。我想避免asyncio;它似乎矯枉過正。它確實闡明瞭錯誤是因爲連接塊時不應該引發錯誤(以及blockingioerror文檔)。問題是'有沒有辦法讓connect()非阻塞'。 – MikeJava