Python Twisted介绍

原文链接:http://www.aosabook.org/en/twisted.html

原文介绍了twisted的历史以及发展现状,对关键的术语进行了阐释,看完之后再看下面的例子就比较明白了。


一个简单的twisted使用示例:

import sys
import os
from twisted.internet.protocol import ServerFactory,ProcessProtocol
from twisted.protocols.basic import LineReceiver
from twisted.python import log
from twisted.internet import reactor


class TailProtocol(ProcessProtocol):
    def __init__(self,write_callback):
        self.write = write_callback


    def outReceived(self,data):
        self.write("Begin lastlog\n")
        data = [line for line in data.split('\n') if not line.startswith('==')]


        for d in data:
            self.write(d+'\n')
        self.write("End lastlog\n")


    def processEnded(self,reason):
        if reason.value.exitCode != 0:
            log.msg(reason)
class HashCompute(object):
    def __init__(self,path,write_callback):
        self.path = path
        self.write = write_callback
    def blockingMethod(self):
        os.path.isfile(self.path)
        data = file(self.path).read()
        return hashlib.sha1(data).hexdigest()


    def compute(self):
        d = threads.deferToThread(self.blockingMethod)
        d.addCallback(self.ret)
        d.addErrback(self.err)


    def ret(self,hdata):
        self.write("file hash is :%s\n"%hdata)


    def err(self,failure):
        self.write("An error occured:%s\n"%failure.getErrorMessage())
        
class CmdProtocol(LineReceiver):
    delimiter='\n'
    def processCmd(self,line):
        if line.startswith('lastlog'):
            tailProtocol = TailProtocol(self.transport.write)
            reactor.spawnProcess(tailProtocol,'/usr/bin/tail',args=['/usr/bin/tail','-10','/var/log/syslog'])
        elif line.startswith('exit'):
            self.transport.loseConnection()
        elif line.startswith('comphash'):
            try:
                useless,path=line.split('')
            except:
                self.transport.write('Please provide a path.\n')
                return
            hc = HashCompute(path,self.transport.write)
            hc.compute()
        else:
            self.transport.write('Command not found.\n')
            
    def connectionMade(self):
        self.client_ip = self.transport.getPeer()
        log.msg('client connection from %s'%self.client_ip)
        if len(self.factory.clients)>=self.factory.clients_max:
            log.msg("too many connections bye!")
            self.client_ip=None
            self.transport.loseConnection()
        else:
            self.factory.clients.append(self.client_ip)


    def connectionLost(self,reason):
        log.msg('Lost client connection. Reason:%s'%reason)
        if self.client_ip:
            self.factory.clients.remove(self.client_ip)


    def lineReceived(self,line):
        log.msg('Cmd received from %s:%s'%(self.client_ip,line))




class MyFactory(ServerFactory):
    protocol = CmdProtocol


    def __init__(self,clients_max=10):
        self.clients_max=clients_max
        self.clients=[]


log.startLogging(sys.stdout)
reactor.listenTCP(9999,MyFactory(2))
reactor.run()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值