python-如何检测客户端何时与UDS断开连接(Unix域套接字)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-如何检测客户端何时与UDS断开连接(Unix域套接字),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2186字,纯文字阅读大概需要4分钟。
内容图文
当客户端连接到管道并发送数据时,我可以收到罚款,并且可以继续接收数据.当客户端断开连接并且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域套接字)全部内容,希望文章能够帮你解决python-如何检测客户端何时与UDS断开连接(Unix域套接字)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。