日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python recv_[Python]关于socket.recv()的非阻塞用法

發(fā)布時(shí)間:2025/3/15 python 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python recv_[Python]关于socket.recv()的非阻塞用法 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Context

在寫(xiě)一個(gè)Socket I/O模塊,功能要求如下:

作為服務(wù)端,需要永遠(yuǎn)循環(huán)等待連接

建立TCP連接后可以收發(fā)數(shù)據(jù)

收發(fā)數(shù)據(jù)相互獨(dú)立,不能阻塞

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)

調(diào)試時(shí)發(fā)現(xiàn)當(dāng)Client沒(méi)有發(fā)送數(shù)據(jù)時(shí),Server會(huì)阻塞地等待接收數(shù)據(jù),也就是data = conn.recv(4096)這一行代碼,導(dǎo)致無(wú)法發(fā)送數(shù)據(jù)。

Solution

查閱queue — A synchronized queue class

后,得知recv()方法需要傳入兩個(gè)參數(shù),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.

文檔內(nèi)只描述了bufsize的用法,關(guān)于flags只是一筆帶過(guò)。

在StackOverflow的When does socket.recv(recv_size) return?問(wèn)題中@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.

得知通過(guò)flags參數(shù)可以將recv()方法設(shè)置為MSG_DONTWAIT,通過(guò)try-except寫(xiě)法可以實(shí)現(xiàn)非阻塞。

代碼如下:

try:

data = conn.recv(4096, 0x40)

except BlockingIOError as e:

data = None

tips: 在查閱了recv(2) - Linux man page文檔后依然沒(méi)能找到0x40和MSG_DONTWAIT的對(duì)照表。

Sunmmary

Python的socket.recv()方法可以通過(guò)傳入flags=0x40參數(shù)配合try-except方法實(shí)現(xiàn)非阻塞。

總結(jié)

以上是生活随笔為你收集整理的python recv_[Python]关于socket.recv()的非阻塞用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。