2015-02-08 26 views
1

我有一臺運行的服務器,它產生了實現前端代理的新TCP端口。我需要能夠移除端口並儘快斷開所有客戶端。如何關閉端口並儘快終止所有活動連接?

factory = ProxyFactory(host, port) 
port = reactor.listenTCP(0, factory) 

後來

port.loseConnection() 

這將關閉端口,但活動連接不營業!我如何關閉端口並終止所有連接?

+0

如果在端口上調用'loseConnection'關閉它,這是實現的一個意外。您正在查找的方法是「stopListening」。這並不能回答你的問題,但它確實指出了其他代碼可能存在的問題。 – 2015-02-08 21:44:03

回答

1

我使用下面的代碼解決了這個問題。 RPC Manager服務器添加新的代理,並的ProxyClient覆蓋twisted.protocols.portforward.ProxyClient

基本上,我必須保持我自己的軌跡客戶端和呼叫abortConnection當我想殺死他們的運輸。

from twisted.internet import protocol, reactor, error 
from twisted.web import xmlrpc, server 
from twisted.python import log, failure 
import socket 

class RPC(xmlrpc.XMLRPC): 
    proxies = {} # (host, port): tcp.Port() 
    clients = [] # list of active client transports 

    def __get(self, host, port): 
     if (host, port) in self.proxies.keys(): 
      return self.proxies.get((host, port)) 
     return self.__new(host, port) 

    def __new(self, host, port): 
     factory = ProxyFactory(host, port) 
     tcp_port = reactor.listenTCP(0, factory) 
     self.proxies[(host, port)] = tcp_port 
     return tcp_port 

    def xmlrpc_get(self, host, port): 
     log.msg('get {}'.format(host, port)) 
     port = self.__get(host, port) 
     return port.getHost().port 

    def xmlrpc_kill(self, host, port): 
     log.msg('kill {}'.format(host, port)) 
     tcp_port = self.proxies.pop((host, port), None) 
     if not tcp_port: 
      return False 
     tcp_port.loseConnection() # don't listen anymore 
     try: 
      ip = socket.gethostbyname(host) 
     except: 
      return False 
     for client in list(self.clients): 
      # kill connections now because we're anxious 
      peer = client.getPeer() 
      if (ip, port) == (peer.host, peer.port): 
       log.msg('abort {}'.format(client)) 
       client.abortConnection() 
       self.clients.remove(client) 
     return True 


class ProxyClient(Proxy): 
    def connectionMade(self): 
     RPC.clients.append(self.transport) 
     self.peer.setPeer(self) 

     # Wire this and the peer transport together to enable 
     # flow control (this stops connections from filling 
     # this proxy memory when one side produces data at a 
     # higher rate than the other can consume). 
     self.transport.registerProducer(self.peer.transport, True) 
     self.peer.transport.registerProducer(self.transport, True) 

     # We're connected, everybody can read to their hearts content. 
     self.peer.transport.resumeProducing() 

    def connectionLost(self, reason): 
     if self.transport in RPC.clients: 
      RPC.clients.remove(self.transport)