|
from twisted.internet.protocol import Protocol, Factory |
|
|
|
|
|
class ServerEcho(Protocol): |
|
|
|
def __init__(self, factory): |
|
|
|
self.factory = factory |
|
|
|
def dataReceived(self, data): |
|
|
|
print('Gonna do an echo of {}'.format(data)) |
|
self.transport.write(data) |
|
|
|
print('Gonna pass along to my registry, too: {}'.format(self.factory.foreign_factory)) |
|
if self.factory.foreign_factory: |
|
for instance in self.factory.foreign_factory.instances: |
|
instance.make_call() |
|
|
|
|
|
class ServerEchoFactory(Factory): |
|
|
|
protocol = ServerEcho |
|
|
|
def __init__(self, foreign_factory=None): |
|
|
|
print('Was passed this: {}'.format(foreign_factory)) |
|
self.foreign_factory = foreign_factory |
|
|
|
def buildProtocol(self, addr): |
|
|
|
instance = self.protocol(self) |
|
|
|
return instance |
|
|
|
|
|
class EchoClient(Protocol): |
|
|
|
def __init__(self, factory): |
|
|
|
self.factory = factory |
|
|
|
def connectionMade(self): |
|
|
|
print("echo client should be registering...") |
|
self.factory.register(self) |
|
print(self.factory.instances) |
|
msg = "Hello server, I am a client!\r\n" |
|
self.send(msg) |
|
|
|
def send(self, msg): |
|
|
|
print("Sending {}".format(msg)) |
|
self.transport.write(msg) |
|
|
|
def connectionLost(self, reason): |
|
|
|
self.factory.unregister(self) |
|
|
|
def make_call(self): |
|
|
|
msg = 'I am an echo client instance, and I just made a call.\r\n' |
|
self.send(msg) |
|
|
|
|
|
class EchoClientFactory(Factory): |
|
|
|
protocol = EchoClient |
|
|
|
def __init__(self): |
|
|
|
self.instances = set() |
|
|
|
def buildProtocol(self, addr): |
|
|
|
instance = self.protocol(self) |
|
|
|
return instance |
|
|
|
def startedConnecting(self, connectorInstance): |
|
|
|
pass |
|
|
|
def clientConnectionLost(self, connection, reason): |
|
|
|
pass |
|
|
|
def register(self, instance): |
|
|
|
self.instances.add(instance) |
|
|
|
return self |
|
|
|
def unregister(self, instance): |
|
|
|
try: |
|
self.instances.remove(instance) |
|
except: |
|
pass |
|
|
|
return self |