1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
5 Client-side of an example for sending file descriptors between processes over
6 UNIX sockets. This client connects to a server listening on a UNIX socket and
7 waits for one file descriptor to arrive over the connection. It displays the
8 name of the file and the first 80 bytes it contains, then exits.
10 To runb this example, run this program with one argument: a path giving the UNIX
11 socket the server side of this example is already listening on. For example:
13 $ python recvfd.py /tmp/sendfd.sock
15 See sendfd.py for the server side of this example.
18 if __name__ == '__main__':
20 raise SystemExit(recvfd.main())
24 from zope.interface import implements
26 from twisted.python.log import startLogging
27 from twisted.python.filepath import FilePath
28 from twisted.internet.defer import Deferred
29 from twisted.internet.interfaces import IFileDescriptorReceiver
30 from twisted.internet.protocol import Factory
31 from twisted.protocols.basic import LineOnlyReceiver
32 from twisted.internet.endpoints import UNIXClientEndpoint
33 from twisted.internet import reactor
35 class ReceiveFDProtocol(LineOnlyReceiver):
36 implements(IFileDescriptorReceiver)
41 self.whenDisconnected = Deferred()
44 def fileDescriptorReceived(self, descriptor):
45 # Record the descriptor sent to us
46 self.descriptor = descriptor
49 def lineReceived(self, line):
50 if self.descriptor is None:
51 print "Received %r without receiving descriptor!" % (line,)
53 # Use the previously received descriptor, along with the newly
54 # provided information about which file it is, to present some
55 # information to the user.
56 data = os.read(self.descriptor, 80)
57 print "Received %r from the server." % (line,)
58 print "First 80 bytes are:\n%r\n" % (data,)
59 os.close(self.descriptor)
60 self.transport.loseConnection()
63 def connectionLost(self, reason):
64 self.whenDisconnected.callback(None)
69 address = FilePath(sys.argv[1])
71 startLogging(sys.stdout)
74 factory.protocol = ReceiveFDProtocol
77 endpoint = UNIXClientEndpoint(reactor, address.path)
78 connected = endpoint.connect(factory)
80 def succeeded(client):
81 return client.whenDisconnected
83 print "Could not connect:", reason.getErrorMessage()
84 def disconnected(ignored):
87 connected.addCallbacks(succeeded, failed)
88 connected.addCallback(disconnected)