I have some problems using asyncore with AF_UNIX sockets. This code
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()
If i execute the code
$ python select_prova.py
writable
handle_connect
handle_write
handle_close
$
It quits immediatly, and doesn’t wait for read and write. If i change code to force writable() method to return always False, it wait correctly for input and i can communicate with socat like this
$ socat readline UNIX:/tmp/mysocket
But only for reading (write logically doesn’t works because writable() returns False). Are there error in my code or I can’t manage AF_UNIX sockets with asyncore/select() ?
Note As the other answer points out, when you send a datagram you need to specify the receiver. As it stands, your
testselectclass looks more like a client than a server.Review some of these
asyncore examplesto find a server pattern you can copy. TheTimeChannelexample is closer to what you want — changesocket.AF_INETtosocket.AF_UNIXand use a socket path for the bind address to have it use a UNIX domain socket.You’re setting
socket.SOCK_DGRAMwhich usually indicates creation of a UDP INET socket. Unix domain sockets are a form of IPC. You should change it tosocket.SOCK_STREAM, callself.listen([backlog]), implementhandle_accept(), etc.If you did intend to use SOCK_DGRAM with AF_UNIX, the reason your server exits is that it is indicating
writableas soon as it’s started, which causeshandle_writeto run, sending the packet containing'buffer'immediately.If you want your server to wait until it’s received a packet before replying, set the buffer in
handle_connectorhandle_read:Now when you start your server it’ll wait until it receives a packet from
socat.I’ve rewritten your example to work more like you indend: