Twisted makes it easy to implement custom network applications. Here's a TCP server that echoes back everything that's written to it:
from twisted.internet import protocol, reactor, endpoints class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) class EchoFactory(protocol.Factory): def buildProtocol(self, addr): return Echo() endpoints.serverFromString(reactor, "tcp:1234").listen(EchoFactory()) reactor.run()
Twisted includes an event-driven web server. Here's a sample web application; notice how the resource object persists in memory, rather than being recreated on each request:
from twisted.web import server, resource from twisted.internet import reactor, endpoints class Counter(resource.Resource): isLeaf = True numberRequests = 0 def render_GET(self, request): self.numberRequests += 1 request.setHeader("content-type", "text/plain") return "I am request #" + str(self.numberRequests) + "\n" endpoints.serverFromString(reactor, "tcp:8080").listen(server.Site(Counter())) reactor.run()
Here's a simple publish/subscribe server, where clients see all messages posted by other clients:
from twisted.internet import reactor, protocol, endpoints from twisted.protocols import basic class PubProtocol(basic.LineReceiver): def __init__(self, factory): self.factory = factory def connectionMade(self): self.factory.clients.add(self) def connectionLost(self, reason): self.factory.clients.remove(self) def lineReceived(self, line): for c in self.factory.clients: c.sendLine("<{}> {}".format(self.transport.getHost(), line)) class PubFactory(protocol.Factory): def __init__(self): self.clients = set() def buildProtocol(self, addr): return PubProtocol(self) endpoints.serverFromString(reactor, "tcp:1025").listen(PubFactory()) reactor.run()
You can test this out by opening two terminals and doing telnet localhost 1025 in each, then typing things.