| 1 |
# Copyright (c) Twisted Matrix Laboratories. |
| 2 |
# See LICENSE for details. |
| 3 |
|
| 4 |
|
| 5 |
""" |
| 6 |
An example client. Run simpleserv.py first before running this. |
| 7 |
""" |
| 8 |
|
| 9 |
from twisted.internet import protocol, reactor |
| 10 |
|
| 11 |
# a client protocol |
| 12 |
|
| 13 |
|
| 14 |
class EchoClient(protocol.Protocol): |
| 15 |
"""Once connected, send a message, then print the result.""" |
| 16 |
|
| 17 |
def connectionMade(self): |
| 18 |
self.transport.write(b"hello, world!") |
| 19 |
|
| 20 |
def dataReceived(self, data): |
| 21 |
"As soon as any data is received, write it back." |
| 22 |
print("Server said:", data) |
| 23 |
self.transport.loseConnection() |
| 24 |
|
| 25 |
def connectionLost(self, reason): |
| 26 |
print("connection lost") |
| 27 |
|
| 28 |
|
| 29 |
class EchoFactory(protocol.ClientFactory): |
| 30 |
protocol = EchoClient |
| 31 |
|
| 32 |
def clientConnectionFailed(self, connector, reason): |
| 33 |
print("Connection failed - goodbye!") |
| 34 |
reactor.stop() |
| 35 |
|
| 36 |
def clientConnectionLost(self, connector, reason): |
| 37 |
print("Connection lost - goodbye!") |
| 38 |
reactor.stop() |
| 39 |
|
| 40 |
|
| 41 |
# this connects the protocol to a server running on port 8000 |
| 42 |
def main(): |
| 43 |
f = EchoFactory() |
| 44 |
reactor.connectTCP("localhost", 8000, f) |
| 45 |
reactor.run() |
| 46 |
|
| 47 |
|
| 48 |
# this only runs if the module was *not* imported |
| 49 |
if __name__ == "__main__": |
| 50 |
main() |