1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | from twisted.internet import reactor from twisted.internet.protocol import Protocol, Factory from webloglib import hit_tag, log_fields import time class WebLog(Protocol): def connectionMade(self): print"Connected from", self.transport.client self.transport.write('<hits>') self.ts = time.time() self.newHits() def newHits(self): for hit in self.factory.records: if self.ts <= hit[0]: self.transport.write(hit_tag % log_fields(hit[1])) self.ts = time.time() reactor.callLater(5, self.newHits) def connectionLost(self, reason): print"Disconnected from", self.transport.client class WebLogFactory(Factory): protocol = WebLog def __init__(self, fname): self.fname = fname self.records = [] def startFactory(self): self.fp = open(self.fname) self.fp.seek(0, 2) # Start at end of current access log self.updateRecords() def updateRecords(self): ts = time.time() for rec in self.fp.readlines(): self.records.append((ts, rec)) self.records = self.records[-100:] # Only keep last 100 hits reactor.callLater(1, self.updateRecords) def stopFactory(self): self.fp.close() if __name__=='__main__': reactor.listenTCP(8888, WebLogFactory('access-log')) reactor.run() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | from twisted.internet.app import Application from twisted.internet.protocol import Protocol, Factory class Fibonacci(Protocol): "Serve a sequence of Fibonacci numbers to all requesters"def dataReceived(self, data): self.factory.new = self.factory.a + self.factory.b self.transport.write('%d' % self.factory.new) self.factory.a = self.factory.b self.factory.b = self.factory.new def main(): import fib_server # Use script as namespace f = Factory() f.protocol = fib_server.Fibonacci f.a, f.b = 1, 1 application = Application("Fibonacci") application.listenTCP(8888, f) application.save() if'__main__' == __name__: main() |
1 2 3 4 5 6 7 | % python fib_server.py % twistd -f Fibonacci.tap ...let server run, then shut it down... % kill `cat twistd.pid` ...re-start server where it left off... % twistd -f Fibonacci-shutdown.tap ...serve numbers where we left off... |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |