Debian Codegraph @

docs/core/examples/starttls_client.py

raw
1 from twisted.internet import defer, endpoints, protocol, ssl, task
2 from twisted.protocols.basic import LineReceiver
3 from twisted.python.modules import getModule
4
5
6 class StartTLSClient(LineReceiver):
7 def connectionMade(self):
8 self.sendLine(b"plain text")
9 self.sendLine(b"STARTTLS")
10
11 def lineReceived(self, line):
12 print("received: ", line)
13 if line == b"READY":
14 self.transport.startTLS(self.factory.options)
15 self.sendLine(b"secure text")
16 self.transport.loseConnection()
17
18
19 @defer.inlineCallbacks
20 def main(reactor):
21 factory = protocol.Factory.forProtocol(StartTLSClient)
22 certData = getModule(__name__).filePath.sibling("server.pem").getContent()
23 factory.options = ssl.optionsForClientTLS(
24 "example.com", ssl.PrivateCertificate.loadPEM(certData)
25 )
26 endpoint = endpoints.HostnameEndpoint(reactor, "localhost", 8000)
27 startTLSClient = yield endpoint.connect(factory)
28
29 done = defer.Deferred()
30 startTLSClient.connectionLost = lambda reason: done.callback(None)
31 yield done
32
33
34 if __name__ == "__main__":
35 import starttls_client
36
37 task.react(starttls_client.main)