用python的twisted做个简单游戏服务器原形--客户端连接monitor管理类

来源:互联网 发布:张卜天的翻译水平知乎 编辑:程序博客网 时间:2024/05/29 03:39
'''Created on 2012-8-14@author: qs'''#from twisted.internet import epollreactor#epollreactor.install()from twisted.internet import selectreactorselectreactor.install()from twisted.internet.protocol import ClientFactory, Protocolfrom twisted.internet import reactorfrom buffer import Bufferimport structimport sysimport threadingfrom msgqueue import MessageQueueclass Service(Protocol):    def __init__(self):        self.index = 0        self.identify = 0        def connectionMade(self):        print "new client come!"        self.factory.service_tick = self.factory.service_tick + 1        self.identify = self.factory.service_tick        self.factory.bind_service(self)            def connectionLost(self, reason):        print "new client lost"        self.factory.unbind_service(self)            def dataReceived(self, data):        message = struct.pack('i%ds' % (len(data)),self.identify,data)        self.factory.push_message(message)                   def dataSend(self, date):        self.transport.write(date)                            class Monitor(ClientFactory, threading.Thread):    protocol = Service        def __init__(self):        threading.Thread.__init__(self)        self.message_queue = MessageQueue(self)        self.service_tick = 0        self.addr = 'localhost'        self.port = 1989            def clientConnectionFailed(self, connector, reason):        print "engine connection failed:", reason.getErrorMessage()        reactor.stop()            def clientConnectionLost(self, connector, reason):        print "engine connection lost:", reason.getErrorMessage()        reactor.stop()            def startedConnecting(self, connector):        print "started connecting engine"            def run(self):        self.message_queue.start()#        monitor_reactor = epollreactor.EPollReactor()        monitor_reactor = selectreactor.SelectReactor()#        monitor_reactor.connectTCP(self.inet_addr.addr, self.inet_addr.port, self)        monitor_reactor.listenTCP(self.port, self)        monitor_reactor.run(installSignalHandlers=False)            def local_addr(self, addr='localhost', port=1989):        self.addr = addr        self.port = port            def bind_service(self, service):        pass        def unbind_service(self, service):        pass        def find_service(self, id):        pass            def push_message(self,message):        self.message_queue.push(message)            def process_message(self, message):        pass
以上是客房端连接有消息连接来的时候一个一monitor类,里面启动了一个线程让reactor运行,一个message_queue线程用来重组客户端发来的消息。
原创粉丝点击