def test_start_up_binds_first_of_real_endpoint_options(self): service = RegionService(sentinel.ipcWorker) # endpoint_1.listen(...) will bind to a random high-numbered port. endpoint_1 = TCP4ServerEndpoint(reactor, 0) # endpoint_2.listen(...), if attempted, will crash because only root # (or a user with explicit capabilities) can do stuff like that. It's # a reasonable assumption that the user running these tests is not # root, but we'll check the port number later too to be sure. endpoint_2 = TCP4ServerEndpoint(reactor, 1) service.endpoints = [[endpoint_1, endpoint_2]] yield service.startService() self.addCleanup(wait_for_reactor(service.stopService)) # A single port has been bound. self.assertThat( service.ports, MatchesAll(HasLength(1), AllMatch(IsInstance(tcp.Port)))) # The port is not listening on port 1; i.e. a belt-n-braces check that # endpoint_2 was not used. [port] = service.ports self.assertThat(port.getHost().port, Not(Equals(1)))
def main(): endpoint = TCP4ServerEndpoint(reactor, 8777) endpoint.listen(ReblockFactory()) #reactor.run() #@UndefinedVariable receiver = TCP4ServerEndpoint(reactor, 8778) receiver.listen(ReceiverFactory()) reactor.run() #@UndefinedVariable
def __init__(self, id, weight): self.id = id self.weight = weight self.endpoint = TCP4ServerEndpoint(reactor, 3344) self.endpoint.listen(PeerFactory()) self.client_port = TCP4ServerEndpoint(reactor, 'localhos', 3344) self.client print('hi i am validator', self.id, self.weight)
def node_run(): print('Node run ...') endpoint = TCP4ServerEndpoint(reactor, 6000, interface=cfg.host) endpoint.listen(MyFactory()) endpoint_2 = TCP4ServerEndpoint(reactor, 7000, interface=cfg.host) endpoint_2.listen(APIFactory()) c = ClientCreator(reactor, ClientProtocol) c.connectTCP(BOOTSTRAP_IP, BOOTSTRAP_PORT).addCallback(gotProtocol) reactor.run()
def __init__(self): # endpoint sending MT messages to the Iridium gateway self.mtIridiumEndpoint = TCP4ClientEndpoint(reactor, 'localhost', 10800) # enpoint receiving MO messages coming from the Iridium network iridiumServerEndpoint = TCP4ServerEndpoint(reactor, 34567) iridiumServerEndpoint.listen(IridiumMoReceiverFactory(self.moMsgCallback)) # interface to QGC #self.qgcInterface = reactor.listenUDP(0, QgcUdpProtocol(self.mtMsgCallback)) qgcInterfaceEndpoint = TCP4ServerEndpoint(reactor, 34568) self.qgcInterface = QgcTcpFactory(self.mtMsgCallback) qgcInterfaceEndpoint.listen(self.qgcInterface) self.mav = mavlink.MAVLink(0)
def main(): # create endpoint state_ep = TCP4ServerEndpoint(reactor, 11000) feedback = TCP4ServerEndpoint(reactor, 11002) # Simple Message client instance for this endpoint client = SimpleMessageServer() feedbackfactory = fb.feedbackfactory() factory = protocol.SimpleMessageFactory(disable_nagle=True) state_ep.listen(factory) feedback.listen(feedbackfactory) print("listening..") reactor.run()
def __init__(self, reactor, filenames): self._reactor = reactor self._peer_id = "-HS0001-"+str(int(time.time())).zfill(12) self._torrents = {} # Send a placeholder for now until the Acceptor is available self._port = 6881 # Set up an amp control channel d = (TCP4ServerEndpoint(reactor, _AMP_CONTROL_PORT, 5, 'localhost') .listen(AMPControlServerFactory(self))) def cannotListen(failure): # Schedule a clean program exit for after the reactor is running self._reactor.callLater(.01, self.quit) logger.critical("Cannot listen on control port localhost:{}" .format(_AMP_CONTROL_PORT)) d.addErrback(cannotListen) # Schedule any torrents named on the command line to be added after # the reactor is running for filename in sys.argv[1:]: self._reactor.callLater(.01, self.add_torrent, (filename)) # The following call starts the reactor HTTPControlServer(self).app.run('localhost', 8080)
def __init__(self, port, transport): self._transport = transport self._port = port self._ep = TCP4ServerEndpoint(reactor, self._port, interface="127.0.0.1") self._crawler = None
def main(): argsGetter = ConfigurationGetter() args = argsGetter.getConfiguration() factory = SyncFactory( args.port, args.password, args.motd_file, args.rooms_db_file, args.permanent_rooms_file, args.isolate_rooms, args.salt, args.disable_ready, args.disable_chat, args.max_chat_message_length, args.max_username_length, args.stats_db_file, args.tls ) endpoint6 = TCP6ServerEndpoint(reactor, int(args.port)) endpoint6.listen(factory).addCallbacks(isListening6, failed6) endpoint4 = TCP4ServerEndpoint(reactor, int(args.port)) endpoint4.listen(factory).addCallbacks(isListening4, failed4) if ServerStatus.listening6 or ServerStatus.listening4: reactor.run() else: print("Unable to listen using either IPv4 and IPv6 protocols. Quitting the server now.") sys.exit()
def main(self, reactor, options): top_service = MultiService() persistence = ConfigurationPersistenceService(reactor, options["data-path"]) persistence.setServiceParent(top_service) cluster_state = ClusterStateService() cluster_state.setServiceParent(top_service) create_api_service( persistence, cluster_state, TCP4ServerEndpoint(reactor, options["port"])).setServiceParent(top_service) amp_service = ControlAMPService( cluster_state, persistence, TCP4ServerEndpoint(reactor, options["agent-port"])) amp_service.setServiceParent(top_service) return main_for_service(reactor, top_service)
def __init__(self, protocol_factory_class, interface='localhost', port=5555, encoding='utf8', timeout=300, logger_name='TCPServer'): """ :param interface: str :param port: int :param encoding: str :param timeout: int :param logger_name: str """ self.interface = interface self.port = port self.log = get_default_logger(logger_name) self._reactor = reactor self._endpoint = TCP4ServerEndpoint(reactor=self._reactor, port=self.port, interface=self.interface) self._endpoint.listen(protocol_factory_class(self)) self.encoding = encoding self.timeout = timeout self.commands = {'stop': self.stop} self.command_processor = CommandProcessor(self.commands, self.log)
def __init__(self, port, delegate): log.info("serving on port %d", port) self.connections = [] self.delegate = delegate endpoint = TCP4ServerEndpoint(reactor, port) delegate.setDispatcher(self) endpoint.listen(SyncFactory(delegate, self))
def main(): print "AndroidProxy --- (C) Mathy Vanhoef" print "This program comes with ABSOLUTELY NO WARRANTY." print print "DNS server will listen on localhost:53" print "HTTP Proxy will listen on localhost:8007" print #print "Physical device: Configure your computer dns server and as router (NOT as proxy) and execute" #print "\tiptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8007" #print "\tiptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8007" #print print "Emulator: start it using: emulator @AvdName -http-proxy http://localhost:8007 -dns-server localhost" print print "Don't forget to start your normal proxy on localhost:8080" print # Setup custom DNS server resolvers = [] resolvers.append(ProxyResolver([('8.8.8.8', 53)])) f = server.DNSServerFactory(clients=resolvers) p = dns.DNSDatagramProtocol(f) reactor.listenUDP(53, p) # Setup TCP proxy server endpoint = TCP4ServerEndpoint(reactor, 8007) endpoint.listen(ProxyFactory('localhost', 8080)) # Start DNS and TCP server reactor.run();
def build_control_amp_service(test_case, reactor=None): """ Create a new ``ControlAMPService``. :param TestCase test_case: The test this service is for. :return ControlAMPService: Not started. """ if reactor is None: reactor = Clock() cluster_state = ClusterStateService(reactor) cluster_state.startService() test_case.addCleanup(cluster_state.stopService) persistence_service = ConfigurationPersistenceService( reactor, test_case.make_temporary_directory()) persistence_service.startService() test_case.addCleanup(persistence_service.stopService) return ControlAMPService( reactor, cluster_state, persistence_service, TCP4ServerEndpoint(MemoryReactor(), 1234), # Easiest TLS context factory to create: ClientContextFactory(), )
def __init__( self, port, connCallback=None, stateCallback=None, sockReadCallback=None, sockStateCallback=None, name="", ): """Construct a socket server Inputs: - port: the port on which to listen for new connections - connCallback: function to call when a client connects; it receives the following arguments: - sock, a Socket - stateCallback: function to call when server changes state; it receives one argument: this server - sockReadCallback: function for each server socket to call when it receives data; See BaseSocket.addReadCallback for details - sockStateCallback: function for each server socket to call when it receives data See BaseSocket.addStateCallback for details - name: a string to identify this socket; strictly optional """ endpoint = TCP4ServerEndpoint(reactor, port=port) Server.__init__( self, endpoint=endpoint, connCallback=connCallback, stateCallback=stateCallback, sockReadCallback=sockReadCallback, sockStateCallback=sockStateCallback, name=name, )
def establish(self, timeout): """ Establishes a server connection. Args: timeout: this parameter will be ignored. Returns: Nothing """ Connection.establish(self, timeout) # Create and configure the endpoint if (not self._useSSL) : endpoint = TCP4ServerEndpoint(reactor, self._port) else : keyPath = self._certificatesDirectory + "/" + "server.key" certificatePath = self._certificatesDirectory + "/" + "server.crt" try : endpoint = SSL4ServerEndpoint(reactor, self._port, ssl.DefaultOpenSSLContextFactory(keyPath, certificatePath)) except Exception: raise ConnectionException("The key, the certificate or both were not found") # Establish the connection def _registerListeningPort(port): self.__listenningPort = port def _onError(error): self._setError(Connection._prettyPrintTwistedError(error)) self._deferred = endpoint.listen(self._factory) # Configure the deferred object self._deferred.addCallback(_registerListeningPort) self._deferred.addErrback(_onError)
def setUp(self): super(TestNettestTimeout, self).setUp() from twisted.internet.protocol import Protocol, Factory from twisted.internet.endpoints import TCP4ServerEndpoint class DummyProtocol(Protocol): def dataReceived(self, data): pass class DummyFactory(Factory): def __init__(self): self.protocols = [] def buildProtocol(self, addr): proto = DummyProtocol() self.protocols.append(proto) return proto def stopFactory(self): for proto in self.protocols: proto.transport.loseConnection() self.factory = DummyFactory() endpoint = TCP4ServerEndpoint(reactor, 8007) self.port = yield endpoint.listen(self.factory) config.advanced.measurement_timeout = 2
def on_start(self): """Exécuté apres build() Lancement du Multicast ou du TCP """ global GLOBAL_DICT freq = int(self.config.get('network', 'freq')) GLOBAL_DICT["freq"] = freq print("Fréquence de réception:", freq) self.cast = self.config.get('network', 'cast') if self.cast == 'multi': # Multicast multi_ip = self.config.get('network', 'multi_ip') multi_port = int(self.config.get('network', 'multi_port')) reactor.listenMulticast(multi_port, MyMulticastServer(self, multi_ip), listenMultiple=True) aaaa = "Multicast server started: ip = {} port = {}" print(aaaa.format(multi_ip, multi_port)) elif self.cast == 'tcp': # TCP tcp_port = int(self.config.get('network', 'tcp_port')) endpoint = TCP4ServerEndpoint(reactor, tcp_port) endpoint.listen(MyTCPServerFactory(self)) print("TCP server started sur le port {}".format(tcp_port)) else: # Si erreur de saisie, forcé en multi self.config.set('network', 'cast', 'multi') self.config.write() self.cast = 'multi' self.on_start()
def listen(self, proto_factory): # we don't care which local TCP port we listen on, but # we do need to know it local_ep = TCP4ServerEndpoint(reactor, 0, interface=u"127.0.0.1") target_port = yield local_ep.listen(proto_factory) tor = yield txtorcon.connect( reactor, tor_control_ep, ) log.info("Creating onion service (descriptor upload can take 30s or more)") hs = yield tor.create_onion_service( ports=[ (port, target_port.getHost().port), ], private_key=private_key, version=version, ) # if it's new, store our private key # XXX better "if private_key is None"? if not exists(private_key_fname): with open(private_key_fname, 'w') as f: f.write(hs.private_key) log.info("Wrote private key to '{fname}'", fname=private_key_fname) log.info( "Listening on Tor onion service {hs.hostname} " " with ports: {ports}", hs=hs, ports=" ".join(hs.ports), ) defer.returnValue(target_port)
def main(): # Read configuration config = SafeConfigParser(defaults={ 'port': '15915', 'plugins_directory': './plugins', 'plugins_enabled': '', }) config.read([ './conf/cm15d.conf', '/etc/cm15d.conf', '/etc/cm15d/cm15d.conf', '/etc/cm15d/conf.d/local.conf', ]) # Activate enabled plugins plugins = PluginManager() plugins.setPluginPlaces( config.get('cm15d', 'plugins_directory').split(',')) plugins.collectPlugins() plugins_enabled = config.get('cm15d', 'plugins_enabled').split(',') for plugin in plugins.getAllPlugins(): if plugin.name in plugins_enabled: plugins.activatePluginByName(plugin.name) print("Plugin %s enabled" % plugin.name) # Start server port = int(config.get('cm15d', 'port')) endpoint = TCP4ServerEndpoint(reactor, port) endpoint.listen(CM15DaemonFactory(plugins)) print("Server listening on port %s" % port) reactor.run()
def connect(self): # Connect to the IP Address endpoint = TCP4ServerEndpoint(reactor, 5000) endpoint.listen(self.factory) # run the server reactor.run()
def my_room_info_packet(context, data): data = bytearray(data) o1, o2, o3, o4 = struct.unpack_from('BBBB', buffer(data), 0x20) ip_string = "%i.%i.%i.%i" % (o1, o2, o3, o4) port = struct.unpack_from('H', buffer(data), 0x28)[0] if port not in blocks.blockList: if verbose: print("[BlockPacket] Discovered a 'My Room' block at %s:%i!" % (ip_string, port)) blocks.blockList[port] = (ip_string, "My Room", port) if port not in blocks.listeningPorts: from ShipProxy import ProxyFactory if bindIp == "0.0.0.0": interface_ip = myIp else: interface_ip = bindIp block_endpoint = TCP4ServerEndpoint(reactor, port, interface=interface_ip) block_endpoint.listen(ProxyFactory()) print("[ShipProxy] Opened listen socked on port %i for new ship." % port) blocks.listeningPorts.append(port) struct.pack_into('BBBB', data, 0x20, int(i0), int(i1), int(i2), int(i3)) context.peer.changingBlocks = True return str(data)
def create_client(self): """ Create a new ``FlockerClient`` instance pointing at a running control service REST API. :return: ``FlockerClient`` instance. """ _, port = find_free_port() self.persistence_service = ConfigurationPersistenceService( reactor, FilePath(self.mktemp())) self.persistence_service.startService() self.cluster_state_service = ClusterStateService(reactor) self.cluster_state_service.startService() self.addCleanup(self.cluster_state_service.stopService) self.addCleanup(self.persistence_service.stopService) credential_set, _ = get_credential_sets() credentials_path = FilePath(self.mktemp()) credentials_path.makedirs() api_service = create_api_service( self.persistence_service, self.cluster_state_service, TCP4ServerEndpoint(reactor, port, interface=b"127.0.0.1"), rest_api_context_factory( credential_set.root.credential.certificate, credential_set.control)) api_service.startService() self.addCleanup(api_service.stopService) credential_set.copy_to(credentials_path, user=True) return FlockerClient(reactor, b"127.0.0.1", port, credentials_path.child(b"cluster.crt"), credentials_path.child(b"user.crt"), credentials_path.child(b"user.key"))
def __init__(self, crawler): self._dump = crawler.settings.getbool('STATS_DUMP') self._stats = {} self.status_websocket = websocketFactory() self.status_websocket.add_stats(self) self.endpoint = TCP4ServerEndpoint(reactor=reactor, port=9998) self.endpoint.listen(self.status_websocket)
def Start(factory): config = ConfigParser.ConfigParser() config.read(GetAppDir() + "/silme.conf") p2p_host = config.get('p2p', 'host') p2p_port = config.get('p2p', 'port') try: endpoint = TCP4ServerEndpoint(reactor, int(p2p_port), interface=p2p_host) logg(" [ ] LISTEN: at %s:%d" % (p2p_host, (int(p2p_port)))) endpoint.listen(factory) except CannotListenError: logg("[!] Address in use") raise SystemExit # connect to bootstrap addresses logg(" [ ] Trying to connect to bootstrap hosts:") for bootstrap in BOOTSTRAP_NODES: logg(" [*] %s" % bootstrap) host, port = bootstrap.split(":") point = TCP4ClientEndpoint(reactor, host, int(port)) d = connectProtocol(point, NCProtocol(factory, "SENDHELLO", "LISTENER")) d.addCallback(gotProtocol) reactor.run(installSignalHandlers=0)
def i2pTunnelCreated(self): if self._writeKeypair: try: f = open(self._keyfile, 'w') f.write(self.keypair) f.close() except IOError: print 'Could not save keypair' # BOB will now forward data to a listener. # BOB only forwards to TCP4 (for now). serverEndpoint = TCP4ServerEndpoint(self._reactor, self.outport) # Wrap the server Factory. wrappedFactory = BOBServerFactoryWrapper(self._serverFactory, self._bobEndpoint, I2PAddress(self.localDest), self.tunnelNick, self.removeTunnelWhenFinished) d = serverEndpoint.listen(wrappedFactory) def handlePort(port): if port is None: self.deferred.cancel() serverAddr = I2PAddress(self.localDest) p = I2PListeningPort(port, wrappedFactory, serverAddr) return p d.addCallback(handlePort) # When the Deferred returns an IListeningPort, pass it on. d.chainDeferred(self.deferred)
def test_returns_service(self): """ ``create_api_service`` returns an object providing ``IService``. """ reactor = MemoryReactor() endpoint = TCP4ServerEndpoint(reactor, 6789) verifyObject(IService, create_api_service(None, None, endpoint))
def start(self): self.endpoint = TCP4ServerEndpoint(reactor, self.port) self.endpoint.listen(self) # Make sure reactor's main thread calls our main() as well reactor.callFromThread(self.main) reactor.run()
def setupWSFactory(factory, port: int) -> None: connType = "WS" if factory.options is not None: endpoint4 = SSL4ServerEndpoint(reactor, port, factory.options) else: endpoint4 = TCP4ServerEndpoint(reactor, port) setupEndpoint(endpoint4, factory, "IPv4", connType)
def run(args=None): """ The main routine. """ cfg = Config() cfg.configure_logger() endpoint = TCP4ServerEndpoint(reactor, cfg.port) logger.info(f"Listening on port {cfg.port}") endpoint.listen(CommandFactory(Wrapper(cfg.config['interface']))) reactor.run()
self.shm_card.get(lock=False).uid = line[5:] self.shm_card.release() time.sleep(0.1) def stop(self): self.running = False if self.nfc_proc is not None: self.nfc_proc.terminate() self.nfc_proc = None if __name__ == '__main__': PORT = 42420 card = shm(Card()) nfc = NFC(card) endpoint = ServerEndpoint(reactor, PORT) endpoint.listen(Factory(card)) def sig_handler(signum, frame): nfc.stop() nfc.join(1) reactor.stop() #signal.signal(signal.SIGTERM, sig_handler) #signal.signal(signal.SIGINT, sig_handler) nfc.start() reactor.run() nfc.stop() nfc.join(1)