def listen_tcp( bind_addresses: Collection[str], port: int, factory: ServerFactory, reactor: IReactorTCP = reactor, backlog: int = 50, ) -> List[Port]: """ Create a TCP socket for a port and several addresses Returns: list of twisted.internet.tcp.Port listening for TCP connections """ r = [] for address in bind_addresses: try: r.append(reactor.listenTCP(port, factory, backlog, address)) except error.CannotListenError as e: check_bind_error(e, address, bind_addresses) # IReactorTCP returns an object implementing IListeningPort from listenTCP, # but we know it will be a Port instance. return r # type: ignore[return-value]
from twisted.internet.interfaces import IReactorTCP from twisted.internet.protocol import Protocol, Factory class SimpleLogger(Protocol): def connectionMade(self): print('got connection from %s' % self.transport.client) def connectionLost(self, reason): print('%s disconnected' % self.transport.client) def dataReceived(self, data): print(data) factory = Factory() factory.protocol = SimpleLogger IReactorTCP.listenTCP(1234, factory) IReactorTCP.Run()