我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用twisted.internet.reactor.listenTCP()。
def main(): log.startLogging(sys.stdout) captchaKey = crypto.getKey(FARFETCHD_CAPTCHA_HMAC_KEYFILE) hmacKey = crypto.getHMAC(captchaKey, "Captcha-Key") # Load or create our encryption keys: secretKey, publicKey = crypto.getRSAKey(FARFETCHD_CAPTCHA_RSA_KEYFILE) index = CaptchaResource() fetch = CaptchaFetchResource(hmacKey, publicKey, secretKey) check = CaptchaCheckResource(hmacKey, publicKey, secretKey) root = index root.putChild("fetch", fetch) root.putChild("check", check) site = HttpJsonApiServer(root) port = FARFETCHD_HTTP_PORT or 80 host = FARFETCHD_HTTP_HOST or '127.0.0.1' reactor.listenTCP(port, site, interface=host) reactor.run()
def get_reactor(): """ :returns: the twisted reactor and the port number for the LDAP server :rtype: tuple """ from twisted.internet import reactor # We initialize our tree tree = Tree() # When the LDAP Server protocol wants to manipulate the DIT, it invokes # `root = interfaces.IConnectedLDAPEntry(self.factory)` to get the root # of the DIT. The factory that creates the protocol must therefore # be adapted to the IConnectedLDAPEntry interface. registerAdapter( lambda x: x.root, LDAPServerFactory, IConnectedLDAPEntry) factory = LDAPServerFactory(tree.db) factory.debug = False listener = reactor.listenTCP(0, factory) port = listener.getHost().port return reactor, port
def main(argv): (logFile, logLevel, listenPort, spoofFavicon, killSessions) = parseOptions(argv) logging.basicConfig(level=logLevel, format='%(asctime)s %(message)s', filename=logFile, filemode='w') URLMonitor.getInstance().setFaviconSpoofing(spoofFavicon) CookieCleaner.getInstance().setEnabled(killSessions) strippingFactory = http.HTTPFactory(timeout=10) strippingFactory.protocol = StrippingProxy reactor.listenTCP(int(listenPort), strippingFactory) print "\nsslstrip " + gVersion + " by Moxie Marlinspike running..." print "+ POC by Leonardo Nve" reactor.run()
def serviceStarted(self): if not options['noshell']: self.openChannel(SSHSession()) if options.localForwards: for localPort, hostport in options.localForwards: reactor.listenTCP(localPort, forwarding.SSHListenForwardingFactory(self, hostport, forwarding.SSHListenClientForwardingChannel)) if options.remoteForwards: for remotePort, hostport in options.remoteForwards: log.msg('asking for remote forwarding for %s:%s' % (remotePort, hostport)) data = forwarding.packGlobal_tcpip_forward( ('0.0.0.0', remotePort)) d = self.sendGlobalRequest('tcpip-forward', data) self.remoteForwards[remotePort] = hostport
def testDistrib(self): # site1 is the publisher r1 = resource.Resource() r1.putChild("there", static.Data("root", "text/plain")) site1 = server.Site(r1) self.f1 = PBServerFactory(distrib.ResourcePublisher(site1)) self.port1 = reactor.listenTCP(0, self.f1) self.sub = distrib.ResourceSubscription("127.0.0.1", self.port1.getHost().port) r2 = resource.Resource() r2.putChild("here", self.sub) f2 = MySite(r2) self.port2 = reactor.listenTCP(0, f2) d = client.getPage("http://127.0.0.1:%d/here/there" % \ self.port2.getHost().port) d.addCallback(self.failUnlessEqual, 'root') return d
def setUp(self): plainRoot = static.Data('not me', 'text/plain') tlsRoot = static.Data('me neither', 'text/plain') plainSite = server.Site(plainRoot, timeout=None) tlsSite = server.Site(tlsRoot, timeout=None) from twisted import test self.tlsPort = reactor.listenSSL(0, tlsSite, contextFactory=ssl.DefaultOpenSSLContextFactory( sibpath(test.__file__, 'server.pem'), sibpath(test.__file__, 'server.pem'), ), interface="127.0.0.1") self.plainPort = reactor.listenTCP(0, plainSite, interface="127.0.0.1") self.plainPortno = self.plainPort.getHost().port self.tlsPortno = self.tlsPort.getHost().port plainRoot.putChild('one', util.Redirect(self.getHTTPS('two'))) tlsRoot.putChild('two', util.Redirect(self.getHTTP('three'))) plainRoot.putChild('three', util.Redirect(self.getHTTPS('four'))) tlsRoot.putChild('four', static.Data('FOUND IT!', 'text/plain'))
def testTcpNoDelay(self): f = MyServerFactory() port = reactor.listenTCP(0, f, interface="127.0.0.1") self.n = port.getHost().port self.ports.append(port) clientF = MyClientFactory() reactor.connectTCP("127.0.0.1", self.n, clientF) d = loopUntil(lambda: (f.called > 0 and getattr(clientF, 'protocol', None) is not None)) def check(x): for p in clientF.protocol, f.protocol: transport = p.transport self.assertEquals(transport.getTcpNoDelay(), 0) transport.setTcpNoDelay(1) self.assertEquals(transport.getTcpNoDelay(), 1) transport.setTcpNoDelay(0) self.assertEquals(transport.getTcpNoDelay(), 0) d.addCallback(check) d.addBoth(lambda _: self.cleanPorts(clientF.protocol.transport, port)) return d
def testClientStartStop(self): f = ClosingFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") self.n = p.getHost().port self.ports.append(p) f.port = p d = loopUntil(lambda :p.connected) def check(ignored): factory = ClientStartStopFactory() reactor.connectTCP("127.0.0.1", self.n, factory) self.assert_(factory.started) return loopUntil(lambda :factory.stopped) d.addCallback(check) d.addBoth(lambda _: self.cleanPorts(*self.ports)) return d
def testReconnect(self): f = ClosingFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) f.port = p factory = MyClientFactory() d = loopUntil(lambda :p.connected) def step1(ignored): def clientConnectionLost(c, reason): c.connect() factory.clientConnectionLost = clientConnectionLost reactor.connectTCP("127.0.0.1", n, factory) return loopUntil(lambda :factory.failed) def step2(ignored): p = factory.protocol self.assertEquals((p.made, p.closed), (1, 1)) factory.reason.trap(error.ConnectionRefusedError) self.assertEquals(factory.stopped, 1) return self.cleanPorts(*self.ports) return d.addCallback(step1).addCallback(step2)
def testCannotBind(self): f = MyServerFactory() p1 = reactor.listenTCP(0, f, interface='127.0.0.1') n = p1.getHost().port self.ports.append(p1) dest = p1.getHost() self.assertEquals(dest.type, "TCP") self.assertEquals(dest.host, "127.0.0.1") self.assertEquals(dest.port, n) # make sure new listen raises error self.assertRaises(error.CannotListenError, reactor.listenTCP, n, f, interface='127.0.0.1') return self.cleanPorts(*self.ports)
def testHostAddress(self): f1 = MyServerFactory() p1 = reactor.listenTCP(0, f1, interface='127.0.0.1') n = p1.getHost().port self.ports.append(p1) f2 = MyOtherClientFactory() p2 = reactor.connectTCP('127.0.0.1', n, f2) d = loopUntil(lambda :p2.state == "connected") def check(ignored): self.assertEquals(p1.getHost(), f2.address) self.assertEquals(p1.getHost(), f2.protocol.transport.getPeer()) return p1.stopListening() def cleanup(ignored): self.ports.append(p2.transport) return self.cleanPorts(*self.ports) return d.addCallback(check).addCallback(cleanup)
def testWriter(self): f = protocol.Factory() f.protocol = WriterProtocol f.done = 0 f.problem = 0 wrappedF = WiredFactory(f) p = reactor.listenTCP(0, wrappedF, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) clientF = WriterClientFactory() wrappedClientF = WiredFactory(clientF) reactor.connectTCP("127.0.0.1", n, wrappedClientF) def check(ignored): self.failUnless(f.done, "writer didn't finish, it probably died") self.failUnless(f.problem == 0, "writer indicated an error") self.failUnless(clientF.done, "client didn't see connection dropped") expected = "".join(["Hello Cleveland!\n", "Goodbye", " cruel", " world", "\n"]) self.failUnless(clientF.data == expected, "client didn't receive all the data it expected") d = defer.gatherResults([wrappedF.onDisconnect, wrappedClientF.onDisconnect]) return d.addCallback(check)
def _testBuildProtocol(self, portno): f = AServerFactory(self, IPv4Address('TCP', '127.0.0.1', portno)) wrappedF = FireOnListenFactory(f) p = reactor.listenTCP(0, wrappedF) self.ports.append(p) def client(ignored): acf = AClientFactory(self, IPv4Address("TCP", "127.0.0.1", p.getHost().port)) wired = WiredFactory(acf) reactor.connectTCP("127.0.0.1", p.getHost().port, wired, bindAddress=("127.0.0.1", portno)) d = wired.onConnect def _onConnect(ignored): self.ports.append(acf.protocol.transport) self.assert_(hasattr(self, "ran")) return wired.onDisconnect def _onDisconnect(ignored): del self.ran d.addCallback(_onConnect) d.addCallback(_onDisconnect) return d return wrappedF.deferred.addCallback(client)
def testWriter(self): f = protocol.Factory() f.protocol = LargeBufferWriterProtocol f.done = 0 f.problem = 0 f.len = self.datalen wrappedF = FireOnCloseFactory(f) p = reactor.listenTCP(0, wrappedF, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) clientF = LargeBufferReaderClientFactory() wrappedClientF = FireOnCloseFactory(clientF) reactor.connectTCP("127.0.0.1", n, wrappedClientF) d = defer.gatherResults([wrappedF.deferred, wrappedClientF.deferred]) def check(ignored): self.failUnless(f.done, "writer didn't finish, it probably died") self.failUnless(clientF.len == self.datalen, "client didn't receive all the data it expected " "(%d != %d)" % (clientF.len, self.datalen)) self.failUnless(clientF.done, "client didn't see connection dropped") return d.addCallback(check)
def testPORTCannotConnect(self): # Login d = self._anonymousLogin() # Listen on a port, and immediately stop listening as a way to find a # port number that is definitely closed. def loggedIn(ignored): port = reactor.listenTCP(0, protocol.Factory(), interface='127.0.0.1') portNum = port.getHost().port d = port.stopListening() d.addCallback(lambda _: portNum) return d d.addCallback(loggedIn) # Tell the server to connect to that port with a PORT command, and # verify that it fails with the right error. def gotPortNum(portNum): return self.assertCommandFailed( 'PORT ' + ftp.encodeHostPort('127.0.0.1', portNum), ["425 Can't open data connection."]) return d.addCallback(gotPortNum) # -- Client Tests -----------------------------------------------------------
def setUp(self): from twisted.internet import reactor self.serverFactory = protocol.ServerFactory() self.serverFactory.protocol = self.serverProto self.clientFactory = protocol.ClientFactory() self.clientFactory.protocol = self.clientProto self.clientFactory.onMade = defer.Deferred() self.serverFactory.onMade = defer.Deferred() self.serverPort = reactor.listenTCP(0, self.serverFactory) self.clientConn = reactor.connectTCP( '127.0.0.1', self.serverPort.getHost().port, self.clientFactory) def getProtos(rlst): self.cli = self.clientFactory.theProto self.svr = self.serverFactory.theProto dl = defer.DeferredList([self.clientFactory.onMade, self.serverFactory.onMade]) return dl.addCallback(getProtos)
def testStopTrying(self): f = Factory() f.protocol = In f.connections = 0 f.allMessages = [] f.goal = 2 f.d = defer.Deferred() c = ReconnectingClientFactory() c.initialDelay = c.delay = 0.2 c.protocol = Out c.howManyTimes = 2 port = self.port = reactor.listenTCP(0, f) PORT = port.getHost().port reactor.connectTCP('127.0.0.1', PORT, c) f.d.addCallback(self._testStopTrying_1, f, c) return f.d
def ftp_PASV(self): """Request for a passive connection from the rfc:: This command requests the server-DTP to \"listen\" on a data port (which is not its default data port) and to wait for a connection rather than initiate one upon receipt of a transfer command. The response to this command includes the host and port address this server is listening on. """ # if we have a DTP port set up, lose it. if self.dtpFactory is not None: # cleanupDTP sets dtpFactory to none. Later we'll do # cleanup here or something. self.cleanupDTP() self.dtpFactory = DTPFactory(pi=self) self.dtpFactory.setTimeout(self.dtpTimeout) self.dtpPort = reactor.listenTCP(0, self.dtpFactory) host = self.transport.getHost().host port = self.dtpPort.getHost().port self.reply(ENTERING_PASV_MODE, encodeHostPort(host, port)) return self.dtpFactory.deferred.addCallback(lambda ign: None)
def setUp(self): self.factory = server.DNSServerFactory([ test_domain_com, reverse_domain, my_domain_com ], verbose=2) p = dns.DNSDatagramProtocol(self.factory) while 1: self.listenerTCP = reactor.listenTCP(0, self.factory, interface="127.0.0.1") port = self.listenerTCP.getHost().port try: self.listenerUDP = reactor.listenUDP(port, p, interface="127.0.0.1") except error.CannotListenError: self.listenerTCP.stopListening() else: break self.resolver = client.Resolver(servers=[('127.0.0.1', port)])
def start(cls, net, factory, bitcoind, peer_ports, merged_urls): self = cls() self.n = node.Node(factory, bitcoind, [], [], net) yield self.n.start() self.n.p2p_node = node.P2PNode(self.n, port=0, max_incoming_conns=1000000, addr_store={}, connect_addrs=[('127.0.0.1', peer_port) for peer_port in peer_ports]) self.n.p2p_node.start() wb = work.WorkerBridge(node=self.n, my_pubkey_hash=random.randrange(2**160), donation_percentage=random.uniform(0, 10), merged_urls=merged_urls, worker_fee=3, args=math.Object(donation_percentage=random.uniform(0, 10), address='foo', worker_fee=3, timeaddresses=1000), pubkeys=main.keypool(), bitcoind=bitcoind) self.wb = wb web_root = resource.Resource() worker_interface.WorkerInterface(wb).attach_to(web_root) self.web_port = reactor.listenTCP(0, server.Site(web_root)) defer.returnValue(self)
def start(cls, net, factory, bitcoind, peer_ports, merged_urls): self = cls() self.n = node.Node(factory, bitcoind, [], [], net) yield self.n.start() self.n.p2p_node = node.P2PNode(self.n, port=0, max_incoming_conns=1000000, addr_store={}, connect_addrs=[('127.0.0.1', peer_port) for peer_port in peer_ports]) self.n.p2p_node.start() wb = work.WorkerBridge(node=self.n, my_pubkey_hash=random.randrange(2**160), donation_percentage=random.uniform(0, 10), merged_urls=merged_urls, worker_fee=3) self.wb = wb web_root = resource.Resource() worker_interface.WorkerInterface(wb).attach_to(web_root) self.web_port = reactor.listenTCP(0, server.Site(web_root)) defer.returnValue(self)
def initialize_web_server(config, validator): # Parse the listen directives from the configuration so # we know what to bind HTTP protocol to listen_directives = parse_listen_directives(config) if 'http' in listen_directives: static_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), "static_content") site = ApiSite(RootPage(validator, static_dir)) interface = listen_directives['http'].host if interface is None: interface = '' LOGGER.info( "listen for HTTP requests on (ip='%s', port=%s)", interface, listen_directives['http'].port) reactor.listenTCP( listen_directives['http'].port, site, interface=interface)
def main(): # ??????? factory = protocol.ServerFactory() # ???ServerFactory?,ServerFactory???factory factory.protocol = EchoServer # ??factory??protocol??,?EchoServer??????protocol reactor.listenTCP(8000, factory, interface="127.0.0.1") # print(type(reactor)) # ??type???reactor??? # twisted.internet.selectreactor.SelectReactor # ??????SelectReactor???twisted.internet.posixbase.PosixReactorBase???? # listenTCP??(port, factory, backlog=50, interface=''),backlog????listen???50 # listenTCP???twisted.internet.tcp.Port? # PosixReactorBase??????twisted.internet.base._SignalReactorMixin,?????????run?? reactor.run() # run?????????startRunning??,startRunning???ReactorBase??startRunning?? # run?????????mainLoop?? # mainLoop?????????SelectReactor.doIteration(t)??,???????????select.select???? # ???????,??self._doReadOrWrite??,??????????twisted.internet.tcp.Connection?doRead??,????? # ??self._dataReceived(data),??????self.protocol.dataReceived(data),??self.protocol???? # ?????protocol.ServerFactory().protocol,????dataReceived(data),????????????,?????listenTCP???factory # ??factory.protocol.dataReceived(data) ????EchoServer().dataReceived(data)??
def global_tcpip_forward(self, data): hostToBind, portToBind = forwarding.unpackGlobal_tcpip_forward(data) from twisted.internet import reactor try: listener = self._runAsUser( reactor.listenTCP, portToBind, forwarding.SSHListenForwardingFactory(self.conn, (hostToBind, portToBind), forwarding.SSHListenServerForwardingChannel), interface = hostToBind) except: return 0 else: self.listeners[(hostToBind, portToBind)] = listener if portToBind == 0: portToBind = listener.getHost()[2] # the port return 1, struct.pack('>L', portToBind) else: return 1
def testTcpKeepAlive(self): f = MyServerFactory() port = reactor.listenTCP(0, f, interface="127.0.0.1") self.n = port.getHost().port self.ports.append(port) clientF = MyClientFactory() reactor.connectTCP("127.0.0.1", self.n, clientF) d = loopUntil(lambda :(f.called > 0 and getattr(clientF, 'protocol', None) is not None)) def check(x): for p in clientF.protocol, f.protocol: transport = p.transport self.assertEquals(transport.getTcpKeepAlive(), 0) transport.setTcpKeepAlive(1) self.assertEquals(transport.getTcpKeepAlive(), 1) transport.setTcpKeepAlive(0) self.assertEquals(transport.getTcpKeepAlive(), 0) d.addCallback(check) d.addBoth(lambda _:self.cleanPorts(clientF.protocol.transport, port)) return d
def testUserFail(self): f = MyServerFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) def startedConnecting(connector): connector.stopConnecting() factory = ClientStartStopFactory() factory.startedConnecting = startedConnecting reactor.connectTCP("127.0.0.1", n, factory) d = loopUntil(lambda :factory.stopped) def check(ignored): self.assertEquals(factory.failed, 1) factory.reason.trap(error.UserError) return self.cleanPorts(*self.ports) return d.addCallback(check)
def run(self, handler): from twisted.web import server, wsgi from twisted.python.threadpool import ThreadPool from twisted.internet import reactor thread_pool = ThreadPool() thread_pool.start() reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop) factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler)) reactor.listenTCP(self.port, factory, interface=self.host) if not reactor.running: reactor.run()
def _doStart(self, tc, port): """Starts the factory""" self.factory = ChatFactory(tc, self._doOnConnectionMade, self._doOnLine) self.port = reactor.listenTCP(int(port), self.factory)
def listen_ip(factory, config, ip_local_default=True, ip_version_default=4): ''' Internal implementation that opens IP listeners for factory based on config. See listen() for details. ''' # upgrade things to lists if they have been passed as single items config = _listify(config) ip_version_default = _listify(ip_version_default) # now process the list listeners = [] for item in config: if not validate_connection_config(item): # warn but skip invalid configs continue if 'port' in item: port = int(item['port']) if 'ip' in item: ip = item['ip'] listeners.append(reactor.listenTCP(port, factory, interface=ip)) else: for ip_version in ip_version_default: ip = IP_LISTEN_DEFAULT[ip_version][ip_local_default] listeners.append(reactor.listenTCP(port, factory, interface=ip)) return _unlistify(listeners)
def starttcpproxy(): reactor.listenTCP(localport, portforward.ProxyFactory(desthost, destport)) reactor.run()
def add_factory(port_map_desc): match = port_map_pattern.match(port_map_desc) if not match: die_usage("malformed port map description: %s" % port_map_desc) listen_port = int(match.group(1)) remote_host = match.group(2) remote_port = int(match.group(3)) factory = HexdumpServerFactory(listen_port, remote_host, remote_port) reactor.listenTCP(factory.listen_port, factory)
def setUp(self): BaseTestCase.setUp(self) self.gw = twisted.TwistedGateway(expose_request=False) root = resource.Resource() root.putChild('', self.gw) self.p = reactor.listenTCP(0, server.Site(root), interface="127.0.0.1") self.port = self.p.getHost().port