Twisted AMP Server连接池

时间:2013-08-09 00:05:19

标签: python twisted

我有一个TCP服务器在扭曲的,侦听tcp客户端上运行。我还有一个Django应用程序,它通过Twisted Server上的AMP向TCP客户端发送消息。

从Djsngo App发送的命令,等待AMP响应,等待TCP客户端响应。

我的问题是发送多个订单,然后AMP Server作为延迟消息可以在破坏的TCP客户端连接上交叉消息,然后我需要一种方法来管理这些订单作为池或其他方式来解决此充电连接

我的AMP服务器

"""Amp Server """
from twisted.protocols.amp import AMP, Command, String

class AmpProcessor(Command):
    arguments = [('proto', String()),
                 ('imei', String()),
                 ('ip', String()),
                 ('port', String()),
                 ('cmmd', String()),
                 ('mssg', String())]
    response = [('answer', String())]

class AMPServer(AMP):

    @AmpProcessor.responder
    def processor(self, proto, imei, ip, port, cmmd, mssg):
        try:
            response = self.factories[proto].clients[ip].runCommand(cmmd, mssg)
            return {'answer': str(response)}
        except:
            return {'answer': str('FAIL')}

我的服务器做的是,当我收到连接时,params得到了

  • Proto:已存储hw TCP客户端的索引
  • Imei:客户身份识别员
  • Ip:客户端连接IP
  • 端口:端口连接
  • Cmmd:Order,这是一个将要执行的方法
  • Mssg:将发送给客户的消息

一旦收到连接,AMP就会检查其存储客户端连接的阵列,并使用该实例发送订单

然后我正在寻找管理连接,类似于没有崩溃客户端连接的池

我的TCP服务器

from twisted.internet import threads
from twisted.internet.protocol import Factory, Protocol

class TrackerServer(Protocol):
    """Tracker Twisted Protocol Class."""

    def __init__(self, clients, devicer):
        self.clients = clients
        self.devicer = devicer
        self.decoder = None
        self.host = None
        self.peer = None
        self.state = False

    def connectionMade(self):
        """ConnectionMade Twisted event."""
        try:
            decoderModule = __import__('listener.protocols.%sDecoder' % (self.devicer, ), fromlist=['%sDecoder' % (self.devicer, )])
            decoderClass = getattr(decoderModule, '%sDecoder' % (self.devicer, ))
            self.decoder = decoderClass()
            self.peer = self.transport.getPeer()
            self.host = self.transport.getHost()
            self.decoder.openConnection(self.host.host, self.host.port, self.peer.host, self.peer.port)
            print 'Connection made to', self.host, 'from', self.peer
            self.clients[self.peer.host] =  self
        except ValueError:
            print "Oops!  Connection was not started"

    def connectionLost(self, reason):
        """ConnectionLost Twisted event."""
        if self.clients.has_key(self.peer.host):
            del self.clients[self.peer.host]
            self.decoder.closeConnection()
            print "Connection lost from", self.peer.host, ':', reason
        else:
            print "Connection unknown peer:", reason

    def dataReceived(self, data):
        """DataReceived Twisted event."""
        #try:
        """ how to precess here a line for a specific client"""
        response = self.decoder.processDatagram(data)
        if  response != False:
            self.sendMessage(response)
            #d = threads.deferToThread(self.factory.decoder.processDatagram(data ))
            #d.addCallback(self.sendResponse)
        #except ValueError:
        #    print "Oops!  That was no valid data.  Try again..."

    def sendMessage (self, response):
        self.transport.write(response)

class TrackerFactory(Factory):

    def __init__(self, devicer):
        self.clients = {}
        self.devicer = devicer

    def buildProtocol(self, addr):
        proto = TrackerServer(self.clients, self.devicer)
        self.connectedProtocol = proto
        return proto

我的* .tac文件

import os, sys
import ConfigParser
from twisted.application import internet, service
from twisted.internet import protocol, reactor
from listener.TrackerServer import TrackerFactory
from listener.AMPServer import AMPServer
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.application.internet import StreamServerEndpointService

PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.append(PROJECT_DIR)

path = None
config = ConfigParser.ConfigParser()
config.read('protocols.cfg')

application = service.Application("tracker")

factories = {}

for device in config.get('protocols', 'keys').split(','):
    devicer = config.get(device, 'name')
    factories[devicer] = TrackerFactory(devicer)
    internet.TCPServer(int(config.get(device, 'port')), factories[devicer]).setServiceParent(application)

endpoint = TCP4ServerEndpoint(reactor, 8750)
factory = Factory()
factory.protocol = AMPServer
factory.protocol.factories = factories
ampService = StreamServerEndpointService(endpoint, factory)
ampService.setServiceParent(application)

0 个答案:

没有答案