gpt4 book ai didi

python - 如何检测客户端何时与 UDS(Unix 域套接字)断开连接

转载 作者:行者123 更新时间:2023-11-28 16:34:41 26 4
gpt4 key购买 nike

当客户端连接到管道并发送数据时,我可以很好地接收到数据,并且可以继续接收数据。当客户端断开连接并且 while 循环仍然处于事件状态时,问题就来了,connection.recv() 不会阻塞,因此会继续疯狂循环!所以我需要一种方法来检测客户端是否仍处于连接状态。

我有以下代码:

    pipe = './pipes/uds_defzone-lrecv'

try:
os.unlink(pipe)
except OSError:
if os.path.exists(pipe):
raise
self.logger.debug('Created UDS pipe: ' + pipe)

sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(pipe)
sock.listen(1)

self.logger.debug('Waiting for connection: ' + pipe)
connection, client_address = sock.accept()
self.logger.debug('Connection from: ' + client_address)

while True:

self.logger.debug('Waiting for data')
data = connection.recv(4096)
self.logger.debug('Received: ' + str(data))

作为引用,sender.py 代码:

# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
pipe = './pipes/uds_defzone-lrecv'

logger.debug('connecting to: ' + pipe)

try:
sock.connect(pipe)
except socket.error, msg:
logger.debug(msg)
sys.exit(1)

try:
message = 'THIS IS A TEST'
logger.debug('sending: ' + message)
sock.sendall(message)
time.sleep(2)

finally:
logger.debug('closing socket')
sock.close()

TIA!

更新

我想我可以用下面的代码减慢它的速度,但不是我想要的。

    while True:

try:
self.logger.debug('Waiting for data')
data_present = select.select([sock], [], [], 30)
if data_present[0]:
data = connection.recv(4096)
self.logger.debug('Received: ' + data)
except select.timeout:
pass

更新 2

作为引用,这是我想出的代码:

        while True:

logger.debug('Waiting for data')
data = connection.recv(4096)
if not data == '':
logger.debug('Received: ' + data)
else:
logger.debug('Nothing received')
break

我在这个过程中想出的一个黑客...可能在客户端可能发送空数据合法的地方可用,也许是为了发信号?

        while True:

try:
logger.debug('Waiting for data')
data = connection.recv(4096)
# *** This throws an exception when client has disconnected
x = connection.getpeername()
logger.debug('Received: ' + data)
except:
logger.debug('Client disconnected')
break

最佳答案

connection.recv() doesn't block and therefore keeps looping frantically! So I need a way to detect if a client is still connected.

如果对等方断开连接,recv 数据将返回空数据 ('')。您需要检查它并退出循环。

关于python - 如何检测客户端何时与 UDS(Unix 域套接字)断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27946786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com