示例#1
0
    def __init__(self, config, fd):

        DaemonThread.__init__(self)
        self.config = config
        if config.get('offline'):
            self.network = None
        else:
            self.network = Network(config)
            self.network.start()
        self.gui = None
        self.wallets = {}
        # Setup server
        cmd_runner = Commands(self.config, None, self.network)
        host = config.get('rpchost', 'localhost')
        port = config.get('rpcport', 0)
        server = SimpleJSONRPCServer((host, port), logRequests=False,
                                     requestHandler=RequestHandler)
        os.write(fd, repr((server.socket.getsockname(), time.time())))
        os.close(fd)
        server.timeout = 0.1
        for cmdname in known_commands:
            server.register_function(getattr(cmd_runner, cmdname), cmdname)
        server.register_function(self.run_cmdline, 'run_cmdline')
        server.register_function(self.ping, 'ping')
        server.register_function(self.run_daemon, 'daemon')
        server.register_function(self.run_gui, 'gui')
        self.server = server
示例#2
0
    def __init__(self, config, fd):

        DaemonThread.__init__(self)
        self.config = config
        if config.get('offline'):
            self.network = None
        else:
            self.network = Network(config)
            self.network.start()
        self.gui = None
        self.wallets = {}
        # Setup server
        cmd_runner = Commands(self.config, None, self.network)
        host = config.get('rpchost', 'localhost')
        port = config.get('rpcport', 0)
        server = SimpleJSONRPCServer((host, port), logRequests=False,
                                     requestHandler=RequestHandler)
        os.write(fd, repr((server.socket.getsockname(), time.time())))
        os.close(fd)
        server.timeout = 0.1
        for cmdname in known_commands:
            server.register_function(getattr(cmd_runner, cmdname), cmdname)
        server.register_function(self.run_cmdline, 'run_cmdline')
        server.register_function(self.ping, 'ping')
        server.register_function(self.run_daemon, 'daemon')
        server.register_function(self.run_gui, 'gui')
        self.server = server
示例#3
0
文件: jsonrpc.py 项目: GemHQ/electrum
class ElectrumGui:

    def __init__(self, config, network):
        self.network = network
        self.config = config
        storage = WalletStorage(self.config.get_wallet_path())
        if not storage.file_exists:
            raise BaseException("Wallet not found")
        self.wallet = Wallet(storage)
        self.cmd_runner = Commands(self.config, self.wallet, self.network)
        host = config.get('rpchost', 'localhost')
        port = config.get('rpcport', 7777)
        self.server = SimpleJSONRPCServer((host, port), requestHandler=RequestHandler)
        self.server.socket.settimeout(1)
        for cmdname in known_commands:
            self.server.register_function(getattr(self.cmd_runner, cmdname), cmdname)

    def main(self, url):
        self.wallet.start_threads(self.network)
        while True:
            try:
                self.server.handle_request()
            except socket.timeout:
                continue
            except:
                break
        self.wallet.stop_threads()
def main():
    """
    The code below starts an JSONRPC server
    """
    from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
    parser = optparse.OptionParser(usage="%prog [OPTIONS]")
    parser.add_option('-p', '--port', default='8080',
                      help='Port to serve on (default 8080)')
    parser.add_option('-H', '--host', default='127.0.0.1',
                      help='Host to serve on (default localhost; 0.0.0.0 to make public)')
    parser.add_option('-q', '--quiet', action='store_false', default=True, dest='verbose',
                      help="Quiet mode, don't print status msgs to stdout")
    parser.add_option('-S', '--corenlp', default=DIRECTORY,
                      help='Stanford CoreNLP tool directory (default %s)' % DIRECTORY)
    parser.add_option('-P', '--properties', default='default.properties',
                      help='Stanford CoreNLP properties fieles (default: default.properties)')
    options, args = parser.parse_args()
    VERBOSE = options.verbose
    # server = jsonrpc.Server(jsonrpc.JsonRpc20(),
    #                         jsonrpc.TransportTcpIp(addr=(options.host, int(options.port))))
    try:
        server = SimpleJSONRPCServer((options.host, int(options.port)))

        nlp = StanfordCoreNLP(options.corenlp, properties=options.properties, serving=True)
        server.register_function(nlp.parse)
        server.register_function(nlp.raw_parse)

        print 'Serving on http://%s:%s' % (options.host, options.port)
        # server.serve()
        server.serve_forever()
    except KeyboardInterrupt:
        print >>sys.stderr, "Bye."
        exit()
def start_master_daemon_func():
    funcs_by_name = {}
    # master_daemon functions
    funcs_by_name['add'] = add
    funcs_by_name['check_connectivity'] = check_connectivity
    funcs_by_name['get_trex_path'] = get_trex_path
    funcs_by_name['update_trex'] = update_trex
    # trex_daemon_server
    funcs_by_name['is_trex_daemon_running'] = trex_daemon_server.is_running
    funcs_by_name['restart_trex_daemon'] = trex_daemon_server.restart
    funcs_by_name['start_trex_daemon'] = trex_daemon_server.start
    funcs_by_name['stop_trex_daemon'] = trex_daemon_server.stop
    # stl rpc proxy
    funcs_by_name['is_stl_rpc_proxy_running'] = stl_rpc_proxy.is_running
    funcs_by_name['restart_stl_rpc_proxy'] = stl_rpc_proxy.restart
    funcs_by_name['start_stl_rpc_proxy'] = stl_rpc_proxy.start
    funcs_by_name['stop_stl_rpc_proxy'] = stl_rpc_proxy.stop
    try:
        set_logger()
        register_socket(master_daemon.tag)
        server = SimpleJSONRPCServer(('0.0.0.0', master_daemon.port))
        logging.info('Started master daemon (port %s)' % master_daemon.port)
        for name, func in funcs_by_name.items():
            server.register_function(partial(log_usage, name, func), name)
        server.register_function(server.funcs.keys, 'get_methods') # should be last
        signal.signal(signal.SIGTSTP, stop_handler) # ctrl+z
        signal.signal(signal.SIGTERM, stop_handler) # kill
        server.serve_forever()
    except KeyboardInterrupt:
        logging.info('Ctrl+C')
    except Exception as e:
        logging.error('Closing due to error: %s' % e)
示例#6
0
def start_master_daemon_func():
    funcs_by_name = {}
    # master_daemon functions
    funcs_by_name['add'] = add
    funcs_by_name['check_connectivity'] = check_connectivity
    funcs_by_name['get_trex_path'] = get_trex_path
    funcs_by_name['update_trex'] = update_trex
    # trex_daemon_server
    funcs_by_name['is_trex_daemon_running'] = trex_daemon_server.is_running
    funcs_by_name['restart_trex_daemon'] = trex_daemon_server.restart
    funcs_by_name['start_trex_daemon'] = trex_daemon_server.start
    funcs_by_name['stop_trex_daemon'] = trex_daemon_server.stop
    # stl rpc proxy
    funcs_by_name['is_stl_rpc_proxy_running'] = stl_rpc_proxy.is_running
    funcs_by_name['restart_stl_rpc_proxy'] = stl_rpc_proxy.restart
    funcs_by_name['start_stl_rpc_proxy'] = stl_rpc_proxy.start
    funcs_by_name['stop_stl_rpc_proxy'] = stl_rpc_proxy.stop
    try:
        set_logger()
        register_socket(master_daemon.tag)
        server = SimpleJSONRPCServer(('0.0.0.0', master_daemon.port))
        logging.info('Started master daemon (port %s)' % master_daemon.port)
        for name, func in funcs_by_name.items():
            server.register_function(partial(log_usage, name, func), name)
        server.register_function(server.funcs.keys, 'get_methods') # should be last
        signal.signal(signal.SIGTSTP, stop_handler) # ctrl+z
        signal.signal(signal.SIGTERM, stop_handler) # kill
        server.serve_forever()
    except KeyboardInterrupt:
        logging.info('Ctrl+C')
    except Exception as e:
        logging.error('Closing due to error: %s' % e)
示例#7
0
def LoadAndServe(host, port):
    server = SimpleJSONRPCServer((host, port))

    for func in API:
        server.register_function(func.values()[0], func.keys()[0])

    server.serve_forever()
示例#8
0
def server_thread(conn):
    from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer

    server = SimpleJSONRPCServer((my_host, my_port))
    server.register_function(process_request, "request")
    server.register_function(do_stop, "stop")
    server.serve_forever()
示例#9
0
class ElectrumGui:
    def __init__(self, config, network):
        self.network = network
        self.config = config
        storage = WalletStorage(self.config.get_wallet_path())
        if not storage.file_exists:
            raise BaseException("Wallet not found")
        self.wallet = Wallet(storage)
        self.cmd_runner = Commands(self.config, self.wallet, self.network)
        host = config.get('rpchost', 'localhost')
        port = config.get('rpcport', 7777)
        self.server = SimpleJSONRPCServer((host, port),
                                          requestHandler=RequestHandler)
        self.server.socket.settimeout(1)
        for cmdname in known_commands:
            self.server.register_function(getattr(self.cmd_runner, cmdname),
                                          cmdname)

    def main(self, url):
        self.wallet.start_threads(self.network)
        while True:
            try:
                self.server.handle_request()
            except socket.timeout:
                continue
            except:
                break
        self.wallet.stop_threads()
示例#10
0
def main():
    """
    The code below starts an JSONRPC server
    """
    from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
    parser = optparse.OptionParser(usage="%prog [OPTIONS]")
    parser.add_option('-p', '--port', default='8080',
                      help='Port to serve on (default 8080)')
    parser.add_option('-H', '--host', default='127.0.0.1',
                      help='Host to serve on (default localhost; 0.0.0.0 to make public)')
    parser.add_option('-q', '--quiet', action='store_false', default=True, dest='verbose',
                      help="Quiet mode, don't print status msgs to stdout")
    parser.add_option('-S', '--corenlp', default=DIRECTORY,
                      help='Stanford CoreNLP tool directory (default %s)' % DIRECTORY)
    parser.add_option('-P', '--properties', default='default.properties',
                      help='Stanford CoreNLP properties fieles (default: default.properties)')
    options, args = parser.parse_args()
    VERBOSE = options.verbose
    # server = jsonrpc.Server(jsonrpc.JsonRpc20(),
    #                         jsonrpc.TransportTcpIp(addr=(options.host, int(options.port))))
    try:
        server = SimpleJSONRPCServer((options.host, int(options.port)))

        nlp = StanfordCoreNLP(options.corenlp, properties=options.properties, serving=True)
        server.register_function(nlp.parse)
        server.register_function(nlp.raw_parse)

        print 'Serving on http://%s:%s' % (options.host, options.port)
        # server.serve()
        server.serve_forever()
    except KeyboardInterrupt:
        print >>sys.stderr, "Bye."
        exit()
示例#11
0
 def init_server(self, config, fd):
     host = config.get('rpchost', '127.0.0.1')
     port = config.get('rpcport', 0)
     try:
         server = SimpleJSONRPCServer((host, port),
                                      logRequests=False,
                                      requestHandler=RequestHandler)
     except Exception as e:
         self.print_error('Warning: cannot initialize RPC server on host',
                          host, e)
         self.server = None
         os.close(fd)
         return
     os.write(
         fd, bytes(repr((server.socket.getsockname(), time.time())),
                   'utf8'))
     os.close(fd)
     server.timeout = 0.1
     for cmdname in known_commands:
         server.register_function(getattr(self.cmd_runner, cmdname),
                                  cmdname)
     server.register_function(self.run_cmdline, 'run_cmdline')
     server.register_function(self.ping, 'ping')
     server.register_function(self.run_daemon, 'daemon')
     server.register_function(self.run_gui, 'gui')
     self.server = server
示例#12
0
def start(host=SERVER_HOST, port=SERVER_PORT):
    # Start RPC server
    server = SimpleJSONRPCServer((host, port))
    server.register_function(add, 'add')
    server.register_function(mazeService.maze_creation, 'maze_creation')
    LOGGER.info("Starting RPC server on %s:%d", host, port)
    server.serve_forever()
示例#13
0
class BackEndPool(Daemon):
    def __init__(self):
        self.backends = {}
        
    def run(self):
        self.server = SimpleJSONRPCServer(('localhost', 8473))
        
        self.server.register_function(self.spawn_backends, "spawn")
        self.server.register_function(self.kill_backends, "kill")
        self.server.serve_forever()
    
    def spawn_backends(self, backend):
        space = backend['space'] 
        model = backend['model']
        if space not in self.backends:
            self.backends[space] = {}
        if model not in self.backends[space]:
            self.backends[space][model] = []
        self.backends[space][model].append(BackEndProcess(backend))
        for be in self.backends[backend['space']][backend['model']]:
            be.start()
        
    def kill_backends(self, backend):
        for be in self.backends[backend['space']][backend['model']]:
            be.join()    
def servidor():
    serverRPC = SimpleJSONRPCServer(('localhost', 7002))
    serverRPC.register_function(criar_novo_jogo)
    serverRPC.register_function(tabuleiro_show)
    # serverRPC.register_function(efetuar_jogada)
    # serverRPC.register_function(jogadas_restantes)
    # serverRPC.register_function(retorna_tabuleiro)
    print("Starting server")
    serverRPC.serve_forever()
示例#15
0
文件: command.py 项目: podhmo/diagrpc
def _main(args):
    server = SimpleJSONRPCServer((args.host, args.port))
    functions = [f for f in args.functions if f in FUNCTION_TABLE]

    _message(functions, args.port)

    for f in functions:
        server.register_function(FUNCTION_TABLE[f])
    server.serve_forever()
示例#16
0
    def __init__(self, host, port):
        srv = SimpleJSONRPCServer((host, port))
        srv.register_introspection_functions()
        srv.register_function(self.ping)

        mc = MissionCache()
        srv.register_instance(mc)

        print "[GameServerService] Up and running!"
        srv.serve_forever()
示例#17
0
 def __init__(self, name, port, cache_size = 100):
   self.name = name
   self.cache = []
   self.cache_size = cache_size
   self.counter = 0
   from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer  # https://pypi.python.org/pypi/jsonrpclib/0.1.6
   server = SimpleJSONRPCServer(('0.0.0.0', port))
   server.register_function(self.count, 'count')
   server.register_function(self.data, 'data')
   print >> log.v3, "json-rpc streaming on port", port
   start_new_thread(server.serve_forever,())
示例#18
0
def server_thread():

    from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer

    host = "127.0.0.1"
    port = int(serverPort)
    #http://user:[email protected]:12345
    server = SimpleJSONRPCServer((host, port), requestHandler=SleuthSimpleJSONRPCRequestHandler, logRequests=True)
    server.register_function(handleRequest, 'sendPost')

    server.serve_forever()
示例#19
0
def start(host=SERVER_HOST, port=SERVER_PORT):
    cloudAMQP_client = CloudAMQPClient(LOG_CLICKS_TASK_QUEUE_URL, LOG_CLICKS_TASK_QUEUE_NAME)

    """ Start rpc server. """
    server = SimpleJSONRPCServer((host, port))
    server.register_function(add, "add")

    # TODO: register your function onto the server.

    LOGGER.info("Starting RPC server on %s:%d", host, port)
    server.serve_forever()
示例#20
0
class JSONRPCapi(threading.Thread):
    def __init__(self, port):
        self.server = SimpleJSONRPCServer(('0.0.0.0', port), logRequests=False)
        self.server.register_instance(apiDispatcher)

        threading.Thread.__init__(self)

    def run(self):
        self.server.serve_forever()

    def register_function(self, *args, **kwargs):
        self.server.register_function(*args, **kwargs)
示例#21
0
文件: rpc.py 项目: c4pt0r/kad
    def __init__(self, ip, port, funcs):
        server = SimpleJSONRPCServer((ip, port), logRequests=False)
        for func in funcs:
            server.register_function(func)

        def _stop():
            pass

        server.register_function(_stop)
        self.server = server
        self.ip = ip
        self.port = port
示例#22
0
文件: __init__.py 项目: DINKIN/XDM
class JSONRPCapi(threading.Thread):

    def __init__(self, port):
        self.server = SimpleJSONRPCServer(('0.0.0.0', port), logRequests=False)
        self.server.register_instance(apiDispatcher)

        threading.Thread.__init__(self)

    def run(self):
        self.server.serve_forever()

    def register_function(self, *args, **kwargs):
        self.server.register_function(*args, **kwargs)
示例#23
0
    def __init__(self, host, port, testing=False, injector=None):
        srv = SimpleJSONRPCServer((host, port))
        srv.register_introspection_functions()
        srv.register_function(self.ping)

        mc = EventServiceMethods()
        srv.register_instance(mc)

        if testing and injector is not None:
            injector.inject(mc)

        print "[GameServerService] Up and running!"
        srv.serve_forever()
示例#24
0
class Browser2DPlot:
    def __init__(self, data=None):
        self.server = SimpleJSONRPCServer(("localhost", 0), encoding="utf8", requestHandler=JSONRPCRequestHandler)
        self.rpc_port = self.server.socket.getsockname()[1]
        self.data = data
        self.server.register_function(self.get_plottable, "get_plottable")
        self.server.register_function(self.kill_server, "shutdown")
        webbrowser.open_new_tab("http://localhost:%d/sliceplot.html" % (self.rpc_port,))
        self.server.serve_forever()

    def get_plottable(self):
        return self.data

    def kill_server(self):
        thread.start_new_thread(self.server.shutdown, ())
示例#25
0
    def register_function(self, rpc_func, rpc_name=None):
        # Patch each registered function to check if the security token
        # matches.
        def patched_rpc_func(*args, **kwargs):
            assert not (args and kwargs)

            # Pop the security token from args or kwargs.
            if args:
                args = list(args)
                rpc_security_token = args.pop(len(args) - 1)
            elif "security_token" in kwargs:
                rpc_security_token = kwargs.pop("security_token")
            else:
                rpc_security_token = None

            # Check the security token argument.
            self._check_security_token(rpc_security_token)

            # Run the RPC function if the security token was acceptable.
            return rpc_func(*args, **kwargs)

        # Preserve the function's name.
        patched_rpc_func.__name__ = rpc_func.__name__

        return SimpleJSONRPCServer.register_function(self, patched_rpc_func,
                                                     rpc_name)
示例#26
0
def startJsonRPC():
    server = SimpleJSONRPCServer(('localhost', 6663))
    server.register_function(lambda x: x, 'echo')
    server.register_function(create_wallet, 'create_wallet')
    server.register_function(import_wallet, 'import_wallet')
    server.register_function(sign_transaction, 'sign_transaction')
    server.register_function(list_wallet_addresses, 'list_wallet_addresses')
    print 'SimpleJSONRPCServer started!'
    server.serve_forever()
示例#27
0
def start(host=SERVER_HOST, port=SERVER_PORT):
    # Start RPC server
    server = SimpleJSONRPCServer((host, port))
    server.register_function(add, 'add')
    server.register_function(get_one_news, 'get_one_news')
    server.register_function(get_news, 'get_news')
    server.register_function(log_news_click_for_user, 'log_news_click_for_user')
    LOGGER.info("Starting RPC server on %s:%d", host, port) 
    server.serve_forever()
示例#28
0
文件: hwi.py 项目: nickw444/Sprinkle
    def main(argv):
        from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
        gpio = GPIOInterface()
        gpio.configure_ports(port_numbers)

        hostname = '127.0.0.1'
        port = 8001
        if '-h' in sys.argv:
            hostname = sys.argv[sys.argv.index('-h') + 1]

        if '-p' in sys.argv:
            port = int(sys.argv[sys.argv.index('-p') + 1])

        s = SimpleJSONRPCServer((hostname, port))
        s.register_function(gpio.set_port)
        s.register_function(gpio.get_port)
        s.serve_forever()
示例#29
0
class JSONRPCServer(SingletonClass):
    def __initialize__(self, context_root='/', server_port=8181):

        SimpleJSONRPCRequestHandler.log_request = log_request
        SimpleJSONRPCRequestHandler.rpc_paths = (context_root)
        self.server = SimpleJSONRPCServer(('', server_port))

    def registerService(self, serviceName, function):
        self.server.register_function(function, name=serviceName)

    def start(self):
        self.server_proc = Thread(target=self.server.serve_forever)
        self.server_proc.daemon = True
        self.server_proc.start()

    def stop(self):
        pass
示例#30
0
def main():
    """
    The code below starts an JSONRPC server
    """
    from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer

    parser = optparse.OptionParser(usage="%prog [OPTIONS]")
    parser.add_option("-p", "--port", default="8080", help="Port to serve on (default 8080)")
    parser.add_option(
        "-H", "--host", default="127.0.0.1", help="Host to serve on (default localhost; 0.0.0.0 to make public)"
    )
    parser.add_option(
        "-q",
        "--quiet",
        action="store_false",
        default=True,
        dest="verbose",
        help="Quiet mode, don't print status msgs to stdout",
    )
    parser.add_option(
        "-S", "--corenlp", default=DIRECTORY, help="Stanford CoreNLP tool directory (default %s)" % DIRECTORY
    )
    parser.add_option(
        "-P",
        "--properties",
        default="default.properties",
        help="Stanford CoreNLP properties fieles (default: default.properties)",
    )
    options, args = parser.parse_args()
    VERBOSE = options.verbose
    # server = jsonrpc.Server(jsonrpc.JsonRpc20(),
    #                         jsonrpc.TransportTcpIp(addr=(options.host, int(options.port))))
    try:
        server = SimpleJSONRPCServer((options.host, int(options.port)))

        nlp = StanfordCoreNLP(options.corenlp, properties=options.properties, serving=True)
        server.register_function(nlp.parse)
        server.register_function(nlp.raw_parse)

        print "Serving on http://%s:%s" % (options.host, options.port)
        # server.serve()
        server.serve_forever()
    except KeyboardInterrupt:
        print >> sys.stderr, "Bye."
        exit()
示例#31
0
def main():
    """
    The code below starts an JSONRPC server
    """
    parser = optparse.OptionParser(usage="%prog [OPTIONS]")
    parser.add_option('-p',
                      '--port',
                      default='8082',
                      help='Port to serve on (default 8082)')
    parser.add_option(
        '-H',
        '--host',
        default='127.0.0.1',
        help='Host to serve on (default localhost; 0.0.0.0 to make public)')
    parser.add_option('-v',
                      '--verbose',
                      action='store_false',
                      default=False,
                      dest='verbose',
                      help="Quiet mode, don't print status msgs to stdout")
    options, args = parser.parse_args()
    VERBOSE = options.verbose
    # server = jsonrpc.Server(jsonrpc.JsonRpc20(),
    #                         jsonrpc.TransportTcpIp(addr=(options.host, int(options.port))))
    try:
        #rh = AllPathRequestHandler if options.ignorepath else SimpleJSONRPCRequestHandler
        rh = SimpleJSONRPCRequestHandler
        server = SimpleJSONRPCServer((options.host, int(options.port)),
                                     requestHandler=rh)
        #inp = '/sc01a7/users/ixamed/BaliabideSemantikoak/SnomedCT_RF1Release_INT_20150131/Terminology/Content/'
        inp = '/ixadata/users/operezdevina001/Doktoretza/kodea/txt2snomed/SnomedCT_RF1Release_eus_20150731'
        des = HierarkiakKargatu(inp)
        server.register_function(des.deskribapenakJaso)
        server.register_function(des.deskribapenArabera)
        server.register_function(des.sct2term)
        server.register_function(des.sct2desc)
        server.register_function(des.sct2hierarkiak)
        server.register_function(des.desc2sct)

        print('Serving on http://%s:%s' % (options.host, options.port))
        # server.serve()
        server.serve_forever()
    except KeyboardInterrupt:
        print(sys.stderr, "Bye.")
        exit()
示例#32
0
class JSONRPCServer(SingletonClass):
    
    def __initialize__(self, context_root='/', server_port=8181):
        
        SimpleJSONRPCRequestHandler.log_request = log_request
        SimpleJSONRPCRequestHandler.rpc_paths = (context_root)
        self.server = SimpleJSONRPCServer(('', server_port))
        
    def registerService(self, serviceName, function):
        self.server.register_function(function, name=serviceName)
        
    def start(self):
        self.server_proc = Thread(target=self.server.serve_forever)
        self.server_proc.daemon = True
        self.server_proc.start()
    
    def stop(self):
        pass
示例#33
0
def main():
    global _PIDS

    # Create a new JSON-RPC server on localhost:8080
    s = SimpleJSONRPCServer(('localhost', 8080))

    # Register the functions to be called by the PHP client
    s.register_function(parse_html, 'parse_html')

    # Creates 5 child server processes
    for i in range(5):
        # Fork current process
        pid = os.fork()

        # Child fork:
        if 0 == pid:
            # Prevent interrupt messages
            for signum in (
                    signal.SIGINT,
                    signal.SIGTERM,
            ):
                signal.signal(signum, _gogentle)

            # Start server
            s.serve_forever()
            os._exit(0)

        # Parent:
        else:
            _PIDS.append(pid)

    # Handle interrupt signals quietly
    for signum in (
            signal.SIGINT,
            signal.SIGTERM,
    ):
        signal.signal(signum, _kronos)

    # Wait for child processes
    while len(_PIDS):
        pid, rc = os.waitpid(-1, 0)
        _PIDS.remove(pid)

    return 0
示例#34
0
def main():
    parser = optparse.OptionParser(usage="%prog [OPTIONS]")
    parser.add_option('-p', '--port', type="int", default=8080,
                      help="Port to bind to [8080]")
    parser.add_option('--path', default=DIRECTORY,
                      help="Path to OpenNLP install [%s]" % DIRECTORY)
    options, args = parser.parse_args()

    addr = ('localhost', options.port)
    uri = 'http://%s:%s' % addr

    server = SimpleJSONRPCServer(addr)

    print("Starting OpenNLP")
    nlp = OpenNLP(options.path)
    server.register_function(nlp.parse)

    print("Serving on %s" % uri)
    server.serve_forever()
示例#35
0
文件: ghost.py 项目: changyc/Overlord
 def StartRPCServer(self):
   logging.info('RPC Server: started')
   rpc_server = SimpleJSONRPCServer((_DEFAULT_BIND_ADDRESS, _GHOST_RPC_PORT),
                                    logRequests=False)
   rpc_server.register_function(self.Reconnect, 'Reconnect')
   rpc_server.register_function(self.GetStatus, 'GetStatus')
   rpc_server.register_function(self.RegisterTTY, 'RegisterTTY')
   rpc_server.register_function(self.RegisterSession, 'RegisterSession')
   rpc_server.register_function(self.AddToDownloadQueue, 'AddToDownloadQueue')
   t = threading.Thread(target=rpc_server.serve_forever)
   t.daemon = True
   t.start()
示例#36
0
class RPCApi():

    functions = []

    def __init__(self, config):
        self.config = config
        self.server = SimpleJSONRPCServer(
            (self.config['rpc_host'], self.config['rpc_port']))
        self.server.timeout = self.config[
            'rpc_timeout'] if "rpc_timeout" in config else 1
        self.server.logRequests = self.config[
            'verbose'] if "verbose" in config else False
        self.register_function(self.list_functions, "list_functions")

    def register_functions(self, **kwargs):
        """Registers functions with the server."""
        for function_name in kwargs:
            function = kwargs[function_name]
            self.register_function(function, function_name)

    def register_function(self, function, function_name):
        """Registers a single function with the server."""
        self.server.register_function(function, function_name)
        self.functions.append(function_name)

    def list_functions(self):
        """An externally accessible function returning all the registered function names"""
        return list(set(self.functions))

    def poll(self):
        """Serves one request from the waiting requests and returns"""
        self.server.handle_request()

    def run(self):
        """Blocks execution and runs the server till the program shutdown"""
        self.server.serve_forever()

    def start_thread(self):
        """Starts self.run() in a separate thread"""
        self.thread = threading.Thread(target=self.run)
        self.thread.daemon = True
        self.thread.start()
示例#37
0
 def StartRPCServer(self):
     logging.info('RPC Server: started')
     rpc_server = SimpleJSONRPCServer(
         (_DEFAULT_BIND_ADDRESS, _GHOST_RPC_PORT), logRequests=False)
     rpc_server.register_function(self.Reconnect, 'Reconnect')
     rpc_server.register_function(self.GetStatus, 'GetStatus')
     rpc_server.register_function(self.RegisterTTY, 'RegisterTTY')
     rpc_server.register_function(self.RegisterSession, 'RegisterSession')
     rpc_server.register_function(self.AddToDownloadQueue,
                                  'AddToDownloadQueue')
     t = threading.Thread(target=rpc_server.serve_forever)
     t.daemon = True
     t.start()
示例#38
0
def server(request):
    """Fixture of environment with Json-Rpc server.

    """
    def close():
        server.shutdown()
        server.server_close()
        thread.join()

    def switch_info(**kwargs):
        return REPLY

    server = SimpleJSONRPCServer((CONFIG["ip_host"], CONFIG["json_port"]))
    # Register method
    server.register_function(switch_info, "getSwitchInfo")

    thread = threading.Thread(target=server.serve_forever)
    thread.start()
    request.addfinalizer(close)
    return server
示例#39
0
文件: daemon.py 项目: bygage/electrum
 def init_server(self, config, fd):
     host = config.get('rpchost', '127.0.0.1')
     port = config.get('rpcport', 0)
     try:
         server = SimpleJSONRPCServer((host, port), logRequests=False, requestHandler=RequestHandler)
     except Exception as e:
         self.print_error('Warning: cannot initialize RPC server on host', host, e)
         self.server = None
         os.close(fd)
         return
     os.write(fd, bytes(repr((server.socket.getsockname(), time.time())), 'utf8'))
     os.close(fd)
     server.timeout = 0.1
     for cmdname in known_commands:
         server.register_function(getattr(self.cmd_runner, cmdname), cmdname)
     server.register_function(self.run_cmdline, 'run_cmdline')
     server.register_function(self.ping, 'ping')
     server.register_function(self.run_daemon, 'daemon')
     server.register_function(self.run_gui, 'gui')
     self.server = server
示例#40
0
def server_thread(conn):
    from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
    server = SimpleJSONRPCServer((my_host, my_port))
    server.register_function(process_request, 'request')
    server.register_function(get_mpk, 'mpk')
    server.register_function(do_stop, 'stop')
    server.serve_forever()
示例#41
0
def server():
    serverRPC = SimpleJSONRPCServer(('localhost', 7002))
    serverRPC.register_function(create_mine_field)
    serverRPC.register_function(play_on_coordinates)
    serverRPC.register_function(get_positions_cleared)
    print("Starting server")
    serverRPC.serve_forever()
示例#42
0
def server_thread(conn):
    from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
    server = SimpleJSONRPCServer(( my_host, my_port))
    server.register_function(process_request, 'request')
    server.register_function(get_mpk, 'mpk')
    server.register_function(do_stop, 'stop')
    server.serve_forever()
示例#43
0
class MockRPCServiceProvider(Thread):
    """Implement a mock of a remote 3rd party JSON-RPC service provider."""

    url = ('localhost', 8484)
    messages = []
    name = ''
    ident = 0

    def __init__(self, *args, **kwargs):
        Thread.__init__(self)
        self.server = SimpleJSONRPCServer(self.url)
        self.server.register_function(self.push, 'push')
        self.server.verbose = False
        self.messages = []

    def run(self):
        logging.debug("MockRPCServiceProvider thread %i start" % self.ident)
        try:
            self.server.serve_forever()
        except:
            pass
        logging.debug("MockRPCServiceProvider thread %i exit" % self.ident)
        exit()

    def stop(self):
        logging.debug("Stop MockRPCServiceProvider")
        self.server.shutdown()
        self.server.server_close()

    def register_function(self,*args,**kwargs):
        return self.server.register_function(*args,**kwargs)

    def push(self, msg, *args):
        logging.debug("saving message: %s" % msg)
        self.messages.append(msg)
        return "ok"

    def get_messages(self):
        return self.messages
示例#44
0
    def test_host_only(self):
        """
        Starts a Unix socket server, giving with a relative path to the socket
        """
        # Ensure we have a new socket
        socket_name = "test_local.socket"
        if os.path.exists(socket_name):
            os.remove(socket_name)

        # Use a random int as result
        awaited_result = random.randint(1, 100)

        try:
            # Prepare the server
            srv = SimpleJSONRPCServer(socket_name,
                                      address_family=socket.AF_UNIX)
            srv.register_function(lambda: awaited_result, "test")

            # Run the server in a thread
            thread = threading.Thread(target=srv.serve_forever)
            thread.start()

            try:
                # Run the request
                client = ServerProxy("unix+http://{}".format(socket_name))
                result = client.test()
                self.assertEqual(result, awaited_result)
            finally:
                # Stop the server
                srv.shutdown()
                srv.server_close()
                thread.join(5)
        finally:
            # Clean up
            try:
                os.remove(socket_name)
            except:
                pass
示例#45
0
class GDFANN_Node:
    def __init__(self, domain='0.0.0.0', port=5000):
        self._server = SimpleJSONRPCServer( (domain, port) )
        functions = {
                     'run' : self.run
                    }

        for name in functions.keys():
            self._server.register_function(functions[name], name)
        self._pop = None

    def run(self, population):
        if type(population) <> list:
            return 'Population must be a list'
        
        if self._pop is not None: del(self._pop)
        
        self._pop = Populacao(None, verboso=True)
        
        for i in population:
            print i
            self._pop.addIndividuo(Cromossomo(9,i))
        
        print 'Evaluating population...'
        self._pop.avaliarPopulacao(avaliacaoRNA)
        print 'Sending answers...'
        answersMSE = []
        for i in self._pop.getIndividuos():
            answersMSE.append(i.getAvaliacao())
        print answersMSE
        return answersMSE

    def serve(self):
        try:
            print 'Server running. Press CTRL+C to stop...'
            self._server.serve_forever()
        except KeyboardInterrupt:
            print 'Exiting'
示例#46
0
class DGFANN_Node:
    def __init__(self, domain='0.0.0.0', port=5000):
        self._server = SimpleJSONRPCServer( (domain, port) )
        functions = {
                     'run' : self.run
                    }

        for name in functions.keys():
            self._server.register_function(functions[name], name)
        self._pop = None

    def run(self, population):
        if type(population) <> list:
            return 'Population must be a list'
        
        if self._pop is not None: del(self._pop)
        
        self._pop = Populacao(None, verboso=True)
        
        for i in population:
            print i
            self._pop.addIndividuo(Cromossomo(9,i))
        
        print 'Evaluating population...'
        self._pop.avaliarPopulacao(avaliacaoRNA)
        print 'Sending answers...'
        answersMSE = []
        for i in self._pop.getIndividuos():
            answersMSE.append(i.getAvaliacao())
        print answersMSE
        return answersMSE

    def serve(self):
        try:
            print 'Server running. Press CTRL+C to stop...'
            self._server.serve_forever()
        except KeyboardInterrupt:
            print 'Exiting'
示例#47
0
def main():
    global _PIDS
 
    # Create a new JSON-RPC server on localhost:8080
    s = SimpleJSONRPCServer(('localhost', 8080))
 
    # Register the functions to be called by the PHP client
    s.register_function(parse_html, 'parse_html')

    # Creates 5 child server processes
    for i in range(5):
        # Fork current process
        pid = os.fork()
 
        # Child fork:
        if 0 == pid:
            # Prevent interrupt messages
            for signum in ( signal.SIGINT, signal.SIGTERM, ):
                signal.signal(signum, _gogentle)
 
            # Start server
            s.serve_forever()
            os._exit(0)
 
        # Parent:
        else:
            _PIDS.append(pid)
 
    # Handle interrupt signals quietly
    for signum in ( signal.SIGINT, signal.SIGTERM, ):
        signal.signal(signum, _kronos)
 
    # Wait for child processes
    while len(_PIDS):
        pid, rc = os.waitpid(-1, 0)
        _PIDS.remove(pid)
 
    return 0
示例#48
0
def main():
    parser = optparse.OptionParser(usage="%prog [OPTIONS]")
    parser.add_option('-p',
                      '--port',
                      type="int",
                      default=8080,
                      help="Port to bind to [8080]")
    parser.add_option('--path',
                      default=DIRECTORY,
                      help="Path to OpenNLP install [%s]" % DIRECTORY)
    options, args = parser.parse_args()

    addr = ('localhost', options.port)
    uri = 'http://%s:%s' % addr

    server = SimpleJSONRPCServer(addr)

    print("Starting OpenNLP")
    nlp = OpenNLP(options.path)
    server.register_function(nlp.parse)

    print("Serving on %s" % uri)
    server.serve_forever()
示例#49
0
def start(host=SERVER_HOST, port=SERVER_PORT):
    RPC_SERVER = SimpleJSONRPCServer((host, port))
    RPC_SERVER.register_function(add, "add")
    RPC_SERVER.register_function(get_one_news, 'get_one_news')
    RPC_SERVER.register_function(log_news_click_for_user,
                                 'logNewsClickForUser')

    logger.info("Starting RPC server on %s: %d", host, port)
    RPC_SERVER.serve_forever()
示例#50
0
 def server_thread():
     from SocketServer import ThreadingMixIn
     from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
     server = SimpleJSONRPCServer(( host, port), requestHandler=authHandler)
     server.register_function(get_new_address, 'getnewaddress')
     server.register_function(get_num, 'getnum')
     server.register_function(get_mpk, 'getkey')
     server.register_function(do_stop, 'stop')
     server.serve_forever()
示例#51
0
 def server_thread():
     from SocketServer import ThreadingMixIn
     from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
     server = SimpleJSONRPCServer((host, port),
                                  requestHandler=authHandler)
     server.register_function(get_new_address, 'getnewaddress')
     server.register_function(get_num, 'getnum')
     server.register_function(get_mpk, 'getkey')
     server.register_function(do_stop, 'stop')
     server.serve_forever()
示例#52
0
class Daemon():
    def __init__(self, config, network):
        self.config = config
        self.network = network
        self.wallets = OrderedDict()
        self.cmd_runner = Commands(self.config, self.wallets, self.network)

        self.server = SimpleJSONRPCServer(('0.0.0.0', config.get('rpc_port')),
                                          requestHandler=RequestHandler,
                                          logRequests=False)
        self.server.timeout = 0.1
        for cmdname in known_commands:
            self.server.register_function(getattr(self.cmd_runner, cmdname),
                                          cmdname)
        self.server.register_function(self.ping, 'ping')
        self.server.register_function(self.run_daemon, 'daemon')

    def ping(self):
        return True

    def run_daemon(self, config):
        sub = config.get('subcommand')
        assert sub in ['start', 'stop', 'status']
        if sub == 'start':
            response = "Daemon already running"
        elif sub == 'status':
            p = self.network.get_parameters()
            response = {
                'path':
                self.network.config.path,
                'server':
                p[0],
                'blockchain_height':
                self.network.get_local_height(),
                'server_height':
                self.network.get_server_height(),
                'nodes':
                self.network.get_interfaces(),
                'connected':
                self.network.is_connected(),
                'auto_connect':
                p[3],
                'wallets':
                dict([(k, w.is_up_to_date())
                      for k, w in self.wallets.items()]),
            }
        elif sub == 'stop':
            self.stop()
            response = "Daemon stopped"
        return response

    def stop(self):
        for k, wallet in self.wallets.items():
            wallet.stop_threads()
        sys.exit()
示例#53
0
def start_server():
    adb = ADB(ADB_PATH)
    funcs = extract_all_the_functions(adb, 'adb_')
    server = SimpleJSONRPCServer((RPC_HOST, RPC_PORT))
    print type(funcs)
    for name, func in funcs.iteritems():
        server.register_function(func)
    server.register_function(lambda x: x, 'ping')
    server.register_function(upload_apk)
    #server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.serve_forever()
示例#54
0
def server_set_up(addr, address_family=socket.AF_INET):
    # Not sure this is a good idea to spin up a new server thread
    # for each test... but it seems to work fine.
    def log_request(self, *args, **kwargs):
        """ Making the server output 'quiet' """
        pass
    SimpleJSONRPCRequestHandler.log_request = log_request
    server = SimpleJSONRPCServer(addr, address_family=address_family)
    service = ExampleAggregateService()
    # Expose an instance of the service
    server.register_instance(service, allow_dotted_names=True)
    # Expose some aliases for service methods
    server.register_function(service.summation, 'sum')
    server.register_function(service.summation, 'notify_sum')
    server.register_function(service.summation, 'namespace.sum')
    server_proc = Thread(target=server.serve_forever)
    server_proc.daemon = True
    server_proc.start()
    return server_proc
示例#55
0
def main():

    print 'Building graph...'
    g = WikiGraph(MAX_NODES)
    with open('datasets/wikipedia.abc', 'r') as fh:
        for i, line in enumerate(fh):
            u, v = line.split()
            g.insert_edge(int(u), int(v))

    print 'Building name dict...'
    names = {}
    with open('datasets/names.map', 'r') as fh:
        for line in fh:
            k, v = line.split()
            names[int(k)] = v


    print 'Starting JSON RPC Server...'
    server = SimpleJSONRPCServer(('localhost', 8080))
    server.register_function(g.successors, 'successors')
    server.register_function(g.predecessors, 'predecessors')
    server.register_function(names.get, 'name')
    server.serve_forever()
示例#56
0
文件: Engine.py 项目: chagge/returnn
  def daemon(self):
    network = self.network
    devices = self.devices
    classifiers = {}

    def _classify(params):
      ret = { }
      output_dim = {}
      hash = hashlib.new('ripemd160')
      hash.update(json.dumps(params))
      hash = hash.hexdigest()
      for k in params:
        try:
          params[k] = numpy.asarray(params[k], dtype='float32')
          if k != 'data':
            output_dim[k] = network.n_out[k] # = [network.n_in,2] if k == 'data' else network.n_out[k]
        except Exception:
          if k != 'data' and not k in network.n_out:
            ret['error'] = 'unknown target: %s' % k
          else:
            ret['error'] = 'unable to convert %s to an array from value %s' % (k,str(params[k]))
          break
      if not 'error' in ret:
        data = StaticDataset(data=[params], output_dim=output_dim)
        data.init_seq_order()
        try:
          data = StaticDataset(data=[params], output_dim=output_dim)
          data.init_seq_order()
        except Exception:
          ret['error'] = "invalid data: %s" % params
        else:
          batches = data.generate_batches(recurrent_net=network.recurrent,
                                          batch_size=sys.maxint, max_seqs=1)
          if not hash in classifiers:
            classifiers[hash] = ClassificationTaskThread(network, devices, data, batches)
            classifiers[hash].json_params = params
            print >> log.v3, "classifier started:", hash
          ret['result'] = { 'hash' : hash }
      return ret

    def _result(hash):
      if not classifiers[hash].isAlive():
        return { 'result' : { k : classifiers[hash].result[k].tolist() for k in classifiers[hash].result } }
      else:
        return { 'error' : "classification in progress"}


    class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
      def do_POST(self):
        if len(self.path) == 0:
          self.send_response(404)
          return
        self.path = self.path[1:]
        ret = {}
        if self.path in ['classify']:
          ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
          if ctype == 'application/json':
            length = int(self.headers.getheader('content-length'))
            params = cgi.parse_qs(self.rfile.read(length),keep_blank_values=1)
            try:
              content = params.keys()[0].decode('utf-8') # this is weird
              params = json.loads(content)
            except Exception:
              ret['error'] = 'unable to decode object'
            else:
              ret.update(_classify(params))
          else:
            ret['error'] = 'invalid header: %s' % ctype
        else:
          ret['error'] = 'invalid command: %s' % self.path
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.wfile.write("\n")
        self.wfile.write(json.dumps(ret))
        self.end_headers()

      def do_GET(self):
        if len(self.path.replace('/', '')) == 0:
          self.send_response(200)
        else:
          if len(self.path) == 0:
            self.send_response(404)
            return
          ret = { 'error' : "" }
          self.path = self.path[1:].split('/')
          if self.path[0] in ['result']:
            if self.path[1] in classifiers:
              if not classifiers[self.path[1]].isAlive():
                ret['result'] = { k : classifiers[self.path[1]].result[k].tolist() for k in classifiers[self.path[1]].result }
              else:
                ret['error'] = "classification in progress"
            else:
              ret['error'] = "unknown hash: " % self.path[1]
          else:
            ret['error'] = "invalid command: %s" % self.path[0]
          self.send_response(200)
          self.send_header('Content-Type', 'application/json')
          self.wfile.write("\n")
          self.wfile.write(json.dumps(ret))
          self.end_headers()

      def log_message(self, format, *args): pass
    class ThreadingServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
      pass

    httpd = ThreadingServer(("", 3333), RequestHandler)
    print >> log.v3, "httpd listening on port", 3333
    try:
      from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer # https://pypi.python.org/pypi/jsonrpclib/0.1.6
    except Exception:
      httpd.serve_forever()
    else:
      from thread import start_new_thread
      start_new_thread(httpd.serve_forever, ())
      server = SimpleJSONRPCServer(('localhost', 3334))
      server.register_function(_classify, 'classify')
      server.register_function(_result, 'result')
      print >> log.v3, "json-rpc listening on port", 3334
      server.serve_forever()
示例#57
0
def create_server(host="127.0.0.1", port=8545):
    server = SimpleJSONRPCServer((host, port), SimpleJSONRPCRequestHandlerWithCORS)
    server.register_function(eth_coinbase, 'eth_coinbase')
    server.register_function(eth_accounts, 'eth_accounts')
    server.register_function(eth_gasPrice, 'eth_gasPrice')
    server.register_function(eth_blockNumber, 'eth_blockNumber')
    server.register_function(eth_call, 'eth_call')
    server.register_function(eth_sendTransaction, 'eth_sendTransaction')
    server.register_function(eth_sendRawTransaction, 'eth_sendRawTransaction')
    server.register_function(eth_getCompilers, 'eth_getCompilers')
    server.register_function(eth_compileSolidity, 'eth_compileSolidity')
    server.register_function(eth_getCode, 'eth_getCode')
    server.register_function(eth_getBalance, 'eth_getBalance')
    server.register_function(eth_getTransactionCount, 'eth_getTransactionCount')
    server.register_function(eth_getTransactionByHash, 'eth_getTransactionByHash')
    server.register_function(eth_getTransactionReceipt, 'eth_getTransactionReceipt')
    server.register_function(eth_getBlockByNumber, 'eth_getBlockByNumber')
    server.register_function(eth_newBlockFilter, 'eth_newBlockFilter')
    server.register_function(eth_newFilter, 'eth_newFilter')
    server.register_function(eth_getFilterChanges, 'eth_getFilterChanges')
    server.register_function(eth_getFilterLogs, 'eth_getFilterLogs')
    server.register_function(eth_uninstallFilter, 'eth_uninstallFilter')
    server.register_function(web3_sha3, 'web3_sha3')
    server.register_function(web3_clientVersion, 'web3_clientVersion')
    server.register_function(evm_reset, 'evm_reset')
    server.register_function(evm_snapshot, 'evm_snapshot')
    server.register_function(evm_revert, 'evm_revert')

    return server
示例#58
0
    # create watching_only wallet
    storage = electrum.WalletStorage(c)
    if not storage.file_exists:
        print "creating wallet file"
        wallet = electrum.wallet.Wallet.from_xpub(xpub, storage)
    else:
        wallet = electrum.wallet.Wallet(storage)

    wallet.synchronize = lambda: None # prevent address creation by the wallet
    wallet.start_threads(network)
    network.register_callback('updated', on_wallet_update)


    threading.Thread(target=db_thread, args=()).start()
    
    out_queue = Queue.Queue()
    # server thread
    from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
    server = SimpleJSONRPCServer(( my_host, my_port))
    server.register_function(process_request, 'request')
    server.register_function(do_dump, 'dump')
    server.register_function(getrequest, 'getrequest')
    server.register_function(do_stop, 'stop')
    server.socket.settimeout(1)
    while not stopping:
        try:
            server.handle_request()
        except socket.timeout:
            continue

示例#59
0
class Daemon(DaemonThread):

    def __init__(self, config, network, gui=None):
        DaemonThread.__init__(self)
        self.config = config
        self.network = network
        self.gui = gui
        self.wallets = {}
        if gui is None:
            self.wallet = self.load_wallet(config)
        else:
            self.wallet = None
        self.cmd_runner = Commands(self.config, self.wallet, self.network)
        host = config.get('rpchost', 'localhost')
        port = config.get('rpcport', 0)
        self.server = SimpleJSONRPCServer((host, port), requestHandler=RequestHandler, logRequests=False)
        with open(lockfile(config), 'w') as f:
            f.write(repr(self.server.socket.getsockname()))
        self.server.timeout = 0.1
        for cmdname in known_commands:
            self.server.register_function(getattr(self.cmd_runner, cmdname), cmdname)
        self.server.register_function(self.run_cmdline, 'run_cmdline')
        self.server.register_function(self.ping, 'ping')
        self.server.register_function(self.run_daemon, 'daemon')
        self.server.register_function(self.run_gui, 'gui')

    def ping(self):
        return True

    def run_daemon(self, config):
        sub = config.get('subcommand')
        assert sub in ['start', 'stop', 'status']
        if sub == 'start':
            response = "Daemon already running"
        elif sub == 'status':
            p = self.network.get_parameters()
            response = {
                'path': self.network.config.path,
                'server': p[0],
                'blockchain_height': self.network.get_local_height(),
                'server_height': self.network.get_server_height(),
                'nodes': self.network.get_interfaces(),
                'connected': self.network.is_connected(),
                'auto_connect': p[4],
                'wallets': self.wallets.keys(),
            }
        elif sub == 'stop':
            self.stop()
            response = "Daemon stopped"
        return response

    def run_gui(self, config_options):
        config = SimpleConfig(config_options)
        if self.gui:
            if hasattr(self.gui, 'new_window'):
                path = config.get_wallet_path()
                self.gui.new_window(path, config.get('url'))
                response = "ok"
            else:
                response = "error: current GUI does not support multiple windows"
        else:
            response = "Error: Electrum is running in daemon mode. Please stop the daemon first."
        return response

    def load_wallet(self, config):
        path = config.get_wallet_path()
        if path in self.wallets:
            wallet = self.wallets[path]
        else:
            storage = WalletStorage(path)
            wallet = Wallet(storage)
            wallet.start_threads(self.network)
            self.wallets[path] = wallet
        return wallet

    def run_cmdline(self, config_options):
        password = config_options.get('password')
        config = SimpleConfig(config_options)
        cmdname = config.get('cmd')
        cmd = known_commands[cmdname]
        wallet = self.load_wallet(config) if cmd.requires_wallet else None
        if wallet:
            wallet.wait_until_synchronized()
        # arguments passed to function
        args = map(lambda x: config.get(x), cmd.params)
        # decode json arguments
        args = map(json_decode, args)
        # options
        args += map(lambda x: config.get(x), cmd.options)
        cmd_runner = Commands(config, wallet, self.network)
        cmd_runner.password = password
        func = getattr(cmd_runner, cmd.name)
        result = func(*args)
        return result

    def run(self):
        while self.is_running():
            self.server.handle_request()
        os.unlink(lockfile(self.config))

    def stop(self):
        for k, wallet in self.wallets.items():
            wallet.stop_threads()
        DaemonThread.stop(self)