gpt4 book ai didi

python - python asyncore 使用 AF_UNIX 套接字的问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:52:01 26 4
gpt4 key购买 nike

我在使用带有 AF_UNIX 套接字的 asyncore 时遇到了一些问题。这段代码

import asyncore, socket, os
class testselect(asyncore.dispatcher):

path = '/tmp/mysocket'

def __init__(self):

asyncore.dispatcher.__init__(self)

self.create_socket(socket.AF_UNIX, socket.SOCK_DGRAM)
self.bind(self.path)
self.buffer = 'buffer'

def handle_connect(self):

print 'handle_connect'
pass

def handle_close(self):
print 'handle_close'
if os.path.exists(self.path)
os.remove(self.path)
self.close()

def handle_read(self):
print 'handle_read'
print self.recv(8192)

def writable(self):
print 'writable'
return (len(self.buffer) > 0)

def handle_write(self):
print 'handle_write'
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]


client = testselect()
asyncore.loop()

如果我执行代码

 $ python select_prova.py
writable
handle_connect
handle_write
handle_close
$

立即退出,不等待读写。如果我更改代码以强制 writable() 方法始终返回 False,它会正确等待输入并且我可以像这样与 socat 通信

 $ socat readline UNIX:/tmp/mysocket

但仅用于读取(逻辑上写入不起作用,因为 writable() 返回 False)。我的代码是否有错误,或者我无法使用 asyncore/select() 管理 AF_UNIX 套接字?

最佳答案

注意 正如其他答案所指出的,发送数据报时需要指定接收方。就目前而言,您的 testselect 类看起来更像是客户端而不是服务器。

回顾其中的一些 asyncore examples找到可以复制的服务器模式。 TimeChannel 示例更接近您想要的——将 socket.AF_INET 更改为 socket.AF_UNIX 并使用套接字路径作为绑定(bind)地址让它使用 UNIX 域套接字。


您正在设置 socket.SOCK_DGRAM,这通常表示创建 UDP INET 套接字。 Unix 域套接字是 IPC 的一种形式。您应该将其更改为socket.SOCK_STREAM,调用self.listen([backlog]),实现handle_accept()等。

如果您打算将 SOCK_DGRAM 与 AF_UNIX 一起使用,您的服务器退出的原因是它在启动后立即指示 writable,这会导致 handle_write 运行,立即发送包含'buffer'的数据包。

如果你想让你的服务器在回复之前等到它收到一个数据包,在 handle_connecthandle_read 中设置缓冲区:

    def __init__(self):
...
self.buffer = ''

def handle_connect(self):
self.buffer = 'buffer'

现在,当您启动服务器时,它会一直等待,直到它收到来自 socat 的数据包。


我已经重写了您的示例,使其工作起来更像您:

import asyncore, socket, os

class testselect(asyncore.dispatcher):

path = '/tmp/mysocket'

def __init__(self):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind(self.path)
self.listen(5)

def handle_accept(self):
client = self.accept()
if client is None:
pass
else:
handler = testhandler(*client)

class testhandler(asyncore.dispatcher_with_send):

def __init__(self, sock, addr):
asyncore.dispatcher_with_send.__init__(self, sock)
self.addr = addr
self.buffer = 'greetings'

def handle_read(self):
print self.recv(8192)

def writable(self):
return (len(self.buffer) > 0)

def handle_write(self):
self.send(self.buffer)
self.buffer = ''

def handle_close(self):
self.close()

server = testselect()
try:
asyncore.loop()
finally:
if os.path.exists(testselect.path):
os.unlink(testselect.path)

关于python - python asyncore 使用 AF_UNIX 套接字的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5994521/

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