Ticket #1442: connect-generic.py

File connect-generic.py, 1.1 KB (added by rwall, 8 years ago)

A simple example of endpoints usage.

Line 
1from twisted.protocols.basic import LineReceiver
2from twisted.internet import endpoints, reactor
3from twisted.internet.address import IPv4Address, UNIXAddress
4from twisted.internet.interfaces import IClientEndpoint, IServerEndpoint
5from twisted.internet.protocol import ClientFactory, ServerFactory
6
7class MyServerProtocol(LineReceiver):
8    def connectionMade(self):
9        self.sendLine("Welcome")
10   
11    def lineReceived(self, line):
12        print "SERVER RECEIVED: ", line, "VIA", self.transport.getHost()         
13
14class MyClientProtocol(LineReceiver):
15    def connectionMade(self):
16        self.sendLine("Hello")
17       
18    def lineReceived(self, line):
19        print "CLIENT RECEIVED: ", line, "VIA", self.transport.getHost() 
20       
21class MyServerFactory(ServerFactory):
22    protocol = MyServerProtocol
23
24class MyClientFactory(ClientFactory):
25    protocol = MyClientProtocol
26
27for addr in (UNIXAddress("/tmp/test.socket"), 
28             IPv4Address("TCP", "127.0.0.1", 10080),):
29    IServerEndpoint(addr).listen(MyServerFactory().buildProtocol)
30    IClientEndpoint(addr).connect(MyClientFactory().buildProtocol)
31
32reactor.callLater(0.1, reactor.stop)
33reactor.run()