python recv_[Python]关于socket.recv()的非阻塞用法
Context
在寫一個Socket I/O模塊,功能要求如下:
作為服務端,需要永遠循環等待連接
建立TCP連接后可以收發數據
收發數據相互獨立,不能阻塞
Trouble
代碼如下
def run_server(send_queue, receive_queue):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print(f"[server] Connecting with {addr}")
with conn:
while True:
try:
m = send_queue.get(block=False)
except queue.Empty as e:
m = None
if m:
print(isinstance(m, AbstractMessage))
if isinstance(m, AbstractMessage):
send_bytes = message2bytes(m)
conn.sendall(send_bytes)
print(f"Send message is {type(m)} : {send_bytes}")
try:
data = conn.recv(4096)
except BlockingIOError as e:
data = None
if data:
print(f"data is {data}")
receive_message = bytes2message(data)
print(f"Receive message is {receive_message}")
receive_queue.put(receive_message)
BUS.push(receive_message)
調試時發現當Client沒有發送數據時,Server會阻塞地等待接收數據,也就是data = conn.recv(4096)這一行代碼,導致無法發送數據。
Solution
查閱queue — A synchronized queue class
后,得知recv()方法需要傳入兩個參數,bufsize和flags:
Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.
文檔內只描述了bufsize的用法,關于flags只是一筆帶過。
在StackOverflow的When does socket.recv(recv_size) return?問題中@Ray的回答:
You can also call recv() as nonblocking if you give the right flag for it: socket.recv(10240, 0x40) # 0x40 = MSG_DONTWAIT a.k.a. O_NONBLOCK Please note that you have to catch the [Errno 11] Resource temporarily unavailable exceptions when there is no input data.
得知通過flags參數可以將recv()方法設置為MSG_DONTWAIT,通過try-except寫法可以實現非阻塞。
代碼如下:
try:
data = conn.recv(4096, 0x40)
except BlockingIOError as e:
data = None
tips: 在查閱了recv(2) - Linux man page文檔后依然沒能找到0x40和MSG_DONTWAIT的對照表。
Sunmmary
Python的socket.recv()方法可以通過傳入flags=0x40參數配合try-except方法實現非阻塞。
總結
以上是生活随笔為你收集整理的python recv_[Python]关于socket.recv()的非阻塞用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ht1621b和单片机电平匹配_有备无患
- 下一篇: 信奥中的数学:孙子定理 中国剩余定理