码迷,mamicode.com
首页 > 其他好文 > 详细

Twisted 库 TCP 服务器 心跳包demo

时间:2014-11-26 19:08:37      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

最近刚刚接触 twisted 库,感觉twisted 库的设计模式和平时接触的socket 通信很大不同, 感觉有点不大适应,为了增加自己对twisted 的适应度, 同时也熟悉一下心跳包的机制。 

特地写了一个  基于twisted 库的 TCP  服务器 心跳包 demo

以供练习之用。 同时也和大家分享 python 编程心得 bubuko.com,布布扣

demo 特性描述:

1   TCP服务器支持多客户端连接, 每次客户端连接之后,直接将客户端信息(IP 地址, 端口号)存储到字典当中。 并且启动Svr_unit 程序定时器(30s 响应)

2  服务器接受到数据之后, 分析 发送数据段的信息 (IP地址,端口号) , 如果数据信息与字典的数据匹配, 则直接调用 对于的Svr_unit 进行数据处理(返回发送数据), 同时刷新定时器,重新定时

3  如果Svr_unit 对象定时器超时, 则调用服务器的函数,将自身从服务器 中的字典中自我移除, 提示连接断开


<span style="font-size:14px;"><span style="font-size:18px;"># -*- coding: utf-8 -*-
"""
Created on 2014/11/25
@author: LEO
"""

from twisted.internet import  protocol, reactor
import  threading


class Svr(object):
    def __init__(self):
        reactor.listenTCP(8000 , svrfactory())

    def Run(self):
        reactor.run()


class svrfactory(protocol.Factory):
    def buildProtocol(self, addr):
        return  Serveport()

class Serveport(protocol.Protocol):
    def __init__(self):
        self._svrunit = dict()

    def connectionMade(self):
        ipinfo = self.transport.getPeer()
        print  ipinfo,'connect server'
        self.Deal_connect(ipinfo)

    def connectionLost(self, reason):
        print 'connection lost for : \n' , reason

    def dataReceived(self, data):
        pipv4 = self.transport.getPeer()
        if data is not None:
            self.Deal_datarecieve(data , pipv4)

    def dataSend(self, data):
        if data is None:
            return
        else:
            self.transport.write(data)

    def Deal_connect(self , pipv4):
        if pipv4 not in self._svrunit:
            print 'new a client' , pipv4
            pclient = Svr_unit( self , pipv4)
            self._svrunit[pipv4] =pclient

    def Deal_disconnect(self ):
        pass

    def Deal_datarecieve(self, data, pipv4):
        if pipv4 in self._svrunit:
            print 'recieve data from ' , pipv4
            self._svrunit[pipv4].Echo(data)
        else:
            print 'warming:'
            print 'recieve data from unknow client' ,pipv4

    def Remove_client(self, pipv4):
        if pipv4 in self._svrunit:
            print 'warming: '
            print pipv4 , 'is over time '
            del self._svrunit[pipv4]
        else:
            print 'not found the client in the list '


class Svr_unit(object):
    def __init__(self,  svrhanle ,pipv4):
        self.srv = svrhanle
        self.ipv4 = pipv4
        # start the timer for heatbeat
        self.timer = threading.Timer(30, self.Terminate )
        self.timer.start()

    def Echo(self , data):
        if data is not None:
            self.Reset_timer()
            pstr = 'echo from server : '+ data
            self.srv.dataSend(pstr)


    def Reset_timer(self):
        """
        reset the anticlock once class had recieve the heart beat signal  """
        print 'reset the timer for heart beat '
        self.timer.cancel()
        self.timer = threading.Timer(20, self.Terminate )
        self.timer.start()

    def Terminate(self):
        '''over time operation :
           remove current class from server list , so that it would never recieve any
           data '''
        self.srv.Remove_client(self.ipv4)


def main():
    svrend = Svr()
    svrend.Run()


if __name__ == '__main__':
    main()
</span></span>

python 编程心得:

1   相比于C++ 编程, python 这种动态脚本语言来实现 面向对象的思想, 那简直是飞一般的感觉。  类之间的相关调用那是行云流水般的舒适。 相互嵌套调用的实现也是非常简单。 用非常少的代码,可是快速实现相当复杂的逻辑关系。 非常棒。 

2  对于python 的编程命令方式, 现在感觉自己非常错乱, 不同的库,采用不同的命名规则, 自己的代码中的变量和函数命名也相当混乱。 希望有人能推荐一种比较适合python 的命名方法,能够解决 python 类内 私有和公有 封装的命名方式

Twisted 库 TCP 服务器 心跳包demo

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://blog.csdn.net/leos_blog/article/details/41517815

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!