示例#1
0
class KeyValueServer:
    _rpc_methods_ = ['get', 'set', 'delete', 'exists', 'keys']
    def __init__(self, address):
        self._data = {}
        self._serv = SimpleXMLRPCServer(address, allow_none=True)
        for name in self._rpc_methods_:
            self._serv.register_function(getattr(self, name))

    def get(self, name):
        return self._data[name]

    def set(self, name, value):
        self._data[name] = value

    def delete(self, name):
        del self._data[name]

    def exists(self, name):
        return name in self._data

    def keys(self):
        return list(self._data)

    def serve_forever(self):
        self._serv.serve_forever()
示例#2
0
class KeyValueServer:
    _rpc_methods = ["get", "set", "exists", "delete", "keys"]

    def __init__(self, address):
        self._data = {}
        self._serv = SimpleXMLRPCServer(address, allow_none=True)
        for method in self._rpc_methods:
            self._serv.register_function(getattr(self, method), method)

    def get(self, name):
        return self._data["name"]

    def set(self, name, value):
        self._data["name"] = value

    def exists(self, name):
        return name in self._data

    def delete(self, name):
        del self._data["name"]

    def keys(self):
        # dict_keys is not supported
        return list(self._data.keys())

    def serve_forever(self):
        self._serv.serve_forever()
 def __init__(self, port=8270, port_file=None):
     SimpleXMLRPCServer.__init__(self, ("127.0.0.1", int(port)))
     self.register_function(self.get_keyword_names)
     self.register_function(self.get_keyword_documentation)
     self.register_function(self.run_keyword)
     announce_port(self.socket, port_file)
     self.serve_forever()
示例#4
0
class Server:

    def __init__(self, address):
        self._rpc_methods_ = ['get', 'put', 'put_back', 'tick', 'keys']
        self._data = {}
        self._serv = SimpleXMLRPCServer(address, allow_none=True)
        for name in self._rpc_methods_:
            self._serv.register_function(getattr(self, name))

    def get(self, key):
        return self._data[key]

    def put(self, key, value):
        self._data[key] = value

    def put_back(self, key, value):
        pass

    def tick(self):
        pass

    def keys(self):
        return list(self._data)

    def serve_forever(self):
        self._serv.serve_forever()
示例#5
0
文件: serv.py 项目: drewmoseley/poky
    def __init__(self, dbfile, logfile, interface, daemon=True):
        ''' constructor '''
        try:
            SimpleXMLRPCServer.__init__(self, interface,
                                        logRequests=False, allow_none=True)
        except socket.error:
            ip=socket.gethostbyname(interface[0])
            port=interface[1]
            msg="PR Server unable to bind to %s:%s\n" % (ip, port)
            sys.stderr.write(msg)
            raise PRServiceConfigError

        self.dbfile=dbfile
        self.daemon=daemon
        self.logfile=logfile
        self.working_thread=None
        self.host, self.port = self.socket.getsockname()
        self.pidfile=PIDPREFIX % (self.host, self.port)

        self.register_function(self.getPR, "getPR")
        self.register_function(self.quit, "quit")
        self.register_function(self.ping, "ping")
        self.register_function(self.export, "export")
        self.register_function(self.dump_db, "dump_db")
        self.register_function(self.importone, "importone")
        self.register_introspection_functions()

        self.requestqueue = queue.Queue()
        self.handlerthread = threading.Thread(target = self.process_request_thread)
        self.handlerthread.daemon = False
 def _start(self):
     """
     Used internally to start the XML-RPC server.
     """
     s = SimpleXMLRPCServer(("", getPort(self.url)), logRequests=False)
     s.register_instance(self)
     s.serve_forever()
示例#7
0
文件: remote.py 项目: woodem/woo
def runServers(xmlrpc=False,tcpPy=False):
    """Run python telnet server and info socket. They will be run at localhost on ports 9000 (or higher if used) and 21000 (or higer if used) respectively.
    
    The python telnet server accepts only connection from localhost,
    after authentication by random cookie, which is printed on stdout
    at server startup.

    The info socket provides read-only access to several simulation parameters
    at runtime. Each connection receives pickled dictionary with those values.
    This socket is primarily used by woo-multi batch scheduler.
    """
    if tcpPy:
        import woo.runtime
        srv=GenericTCPServer(handler=woo.remote.PythonConsoleSocketEmulator,title='TCP python prompt',cookie=True,minPort=9000)
        woo.runtime.cookie=srv.server.cookie
    if xmlrpc:
        if future.utils.PY3: from xmlrpc.server import SimpleXMLRPCServer
        else: from SimpleXMLRPCServer import SimpleXMLRPCServer
        port,maxPort=21000,65535 # minimum port number
        while port<maxPort:
            try:
                info=SimpleXMLRPCServer(('',port),logRequests=False,allow_none=True); break
            except socket.error: port+=1
        if port==maxPort: raise RuntimeError("No free port to listen on in range 21000-%d"%maxPort)
        # register methods, as per http://docs.python.org/library/simplexmlrpcserver.html#simplexmlrpcserver-example
        info.register_instance(InfoProvider()) # gets all defined methods by introspection
        #prov=InfoProvider()
        #for m in prov.exposedMethods(): info.register_function(m)
        _runInBackground(info.serve_forever)
        print('XMLRPC info provider on http://localhost:%d'%port)
    sys.stdout.flush()
示例#8
0
文件: xmlrpc.py 项目: Aand1/ROSCH
 def __init__(self, addr, log_requests=1):
     """
     Overrides SimpleXMLRPCServer to set option to allow_reuse_address.
     """
     # allow_reuse_address defaults to False in Python 2.4.  We set it 
     # to True to allow quick restart on the same port.  This is equivalent 
     # to calling setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
     self.allow_reuse_address = True
     if rosgraph.network.use_ipv6():
         logger = logging.getLogger('xmlrpc')
         # The XMLRPC library does not support IPv6 out of the box
         # We have to monipulate private members and duplicate
         # code from the constructor.
         # TODO IPV6: Get this into SimpleXMLRPCServer 
         SimpleXMLRPCServer.__init__(self, addr, SilenceableXMLRPCRequestHandler, log_requests,  bind_and_activate=False)
         self.address_family = socket.AF_INET6
         self.socket = socket.socket(self.address_family, self.socket_type)
         logger.info('binding ipv6 xmlrpc socket to' + str(addr))
         # TODO: set IPV6_V6ONLY to 0:
         # self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
         self.server_bind()
         self.server_activate()
         logger.info('bound to ' + str(self.socket.getsockname()[0:2]))
     else:
         SimpleXMLRPCServer.__init__(self, addr, SilenceableXMLRPCRequestHandler, log_requests)
示例#9
0
 def __init__(self, addr, log_requests=1):
     """
     Overrides SimpleXMLRPCServer to set option to allow_reuse_address.
     """
     # allow_reuse_address defaults to False in Python 2.4.  We set it 
     # to True to allow quick restart on the same port.  This is equivalent 
     # to calling setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
     self.allow_reuse_address = True
     if rosgraph.network.use_ipv6():
         logger = logging.getLogger('xmlrpc')
         # The XMLRPC library does not support IPv6 out of the box
         # We have to monipulate private members and duplicate
         # code from the constructor.
         # TODO IPV6: Get this into SimpleXMLRPCServer 
         SimpleXMLRPCServer.__init__(self, addr, SilenceableXMLRPCRequestHandler, log_requests,  bind_and_activate=False)
         self.address_family = socket.AF_INET6
         self.socket = socket.socket(self.address_family, self.socket_type)
         logger.info('binding ipv6 xmlrpc socket to' + str(addr))
         # TODO: set IPV6_V6ONLY to 0:
         # self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
         self.server_bind()
         self.server_activate()
         logger.info('bound to ' + str(self.socket.getsockname()[0:2]))
         # TODO IPV6: check Windows compatibility
         # [Bug #1222790] If possible, set close-on-exec flag; if a
         # method spawns a subprocess, the subprocess shouldn't have
         # the listening socket open.
         if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
             flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
             flags |= fcntl.FD_CLOEXEC
             fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
     else:
         SimpleXMLRPCServer.__init__(self, addr, SilenceableXMLRPCRequestHandler, log_requests)
 def __init__(self, library, port=8270, port_file=None):
     SimpleXMLRPCServer.__init__(self, ('127.0.0.1', int(port)))
     self.library = library
     self._shutdown = False
     self._register_functions()
     announce_port(self.socket, port_file)
     self.serve_forever()
def run_xmlrpc_server():
  port = 1210
  oo_proxy = OOProxy()
  #server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", port))
  server = SimpleXMLRPCServer(("localhost", port))
  server.register_instance(oo_proxy)
  #Go into the main listener loop
  server.serve_forever()
示例#12
0
    def test_exposeFunction1(self):
        """Expose a function via XML-RPC."""
        server = SimpleXMLRPCServer((HOST, PORT + 1))
        server.register_function(multiply)
        ServerThread(server).start()

        # Access the exposed service.
        client = xmlrpc.client.ServerProxy("http://%s:%d" % (HOST, PORT + 1))
        self.assertEqual(client.multiply(5, 10), 50)
示例#13
0
    def test_exposeFunction2(self):
        """Expose a function using a different name via XML-RPC."""
        server = SimpleXMLRPCServer((HOST, PORT + 2))
        server.register_function(multiply, "mult")
        ServerThread(server).start()

        # Access the exposed service.
        client = xmlrpc.client.ServerProxy("http://%s:%d" % (HOST, PORT + 2))
        self.assertEqual(client.mult(7, 11), 77)
示例#14
0
    def test_exposeClass(self):
        """Expose an entire class and test the _dispatch method."""
        server = SimpleXMLRPCServer((HOST, PORT + 3))
        server.register_instance(MyService())
        ServerThread(server).start()

        # Access the exposed service.
        client = xmlrpc.client.ServerProxy("http://%s:%d" % (HOST, PORT + 3))
        self.assertEqual(client.squared(10), 100)
def main():
    server = SimpleXMLRPCServer(("localhost", PORT))
    print("We've got a connection and are listening on port {}...huzzah".format(PORT))

    # 注册函数,这样它可以被即将创建的客户端代码使用
    server.register_function(square, "square")

    # 启动服务器
    server.serve_forever()
示例#16
0
 def __init__(self, addr, log_requests=1):
     """
     Overrides SimpleXMLRPCServer to set option to allow_reuse_address.
     """
     # allow_reuse_address defaults to False in Python 2.4.  We set it 
     # to True to allow quick restart on the same port.  This is equivalent 
     # to calling setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
     self.allow_reuse_address = True
     SimpleXMLRPCServer.__init__(self, addr, SilenceableXMLRPCRequestHandler, log_requests)
示例#17
0
文件: judged.py 项目: leafduo/syoj
def buildServer():
    """build an XMLRPC Server and serve forever \
    waiting for problem to submit.
    """
    global config
    server = SimpleXMLRPCServer((config.get("XMLRPCServer","host"), \
		    config.getint("XMLRPCServer","port")))
    server.register_function(receive, "send")
    server.serve_forever()
 def __init__(self, library, port=8270, port_file=None):
     SimpleXMLRPCServer.__init__(self, ('127.0.0.1', int(port)))
     self.library = library
     self._shutdown = False
     self.register_function(self.get_keyword_names)
     self.register_function(self.get_keyword_arguments)
     self.register_function(self.run_keyword)
     announce_port(self.socket, port_file)
     self.serve_forever()
示例#19
0
class DebugStubComm(object):

    def __init__(self, stub, port):
        self.stub = stub
        addr = "0.0.0.0"
        self.server = SimpleXMLRPCServer((addr, port))
        self.server.register_function(self.handshake)
        self.server.register_function(self.get_agent_list)
        self.server.register_function(self.track_agent)
        self.server.register_function(self.get_agent_track)


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

    ###########################################################################
    # client side api
    ###########################################################################
    def get_agent_list(self):
        self.stub.lock.acquire()
        l = [i for i in self.stub.agents]
        self.stub.lock.release()
        return l

    def handshake(self):
        return True

    def track_agent(self, agent_id, on_off):
        self.stub.lock.acquire()
        if agent_id not in self.stub.agents:
            self.stub.lock.release()
            return False
        agent = self.stub.agents[agent_id]
        agent.tracked = on_off
        self.stub.lock.release()
        return True

    def get_agent_track(self, agent_id):
        self.stub.lock.acquire()
        if agent_id not in self.stub.agents:
            self.stub.lock.release()
            return False
        agent = self.stub.agents[agent_id]
        ret = agent.history
        agent.history = []
        self.stub.lock.release()
        return ret

    def set_breakpoint(self, agent_id, location_info):
        pass

    def remove_breakpoint(self, agent_id, location_info):
        pass

    def continue_agent(self, agent_id):
        pass
示例#20
0
def start():
    #NOTE: bots directory should always be on PYTHONPATH - otherwise it will not start.
    #***command line arguments**************************
    usage = '''
    This is "%(name)s" version %(version)s, part of Bots open source edi translator (http://bots.sourceforge.net).
    Server program that ensures only a single bots-engine runs at any time, and no engine run requests are
    lost/discarded. Each request goes to a queue and is run in sequence when the previous run completes.
    Use of the job queue is optional and must be configured in bots.ini (jobqueue section, enabled = True).
    Usage:
        %(name)s  -c<directory>
    Options:
        -c<directory>   directory for configuration files (default: config).

    ''' % {'name': os.path.basename(sys.argv[0]), 'version': 3.3}
    configdir = 'config'
    for arg in sys.argv[1:]:
        if arg.startswith('-c'):
            configdir = arg[2:]
            if not configdir:
                print('Error: configuration directory indicated, but no directory name.')
                sys.exit(1)
        else:
            print(usage)
            sys.exit(0)
    #***end handling command line arguments**************************
    #~ botsinit.generalinit(configdir)     #find locating of bots, configfiles, init paths etc.
    #~ if not botsglobal.ini.getboolean('jobqueue','enabled',False):
        #~ print('Error: bots jobqueue cannot start; not enabled in %s/bots.ini'%(configdir))
        #~ sys.exit(1)
    nr_threads = 2  # botsglobal.ini.getint('jobqueue','nr_threads')
    process_name = 'jobqueue'
    #~ logger = botsinit.initserverlogging(process_name)
    #~ logger.log(25,'Bots %(process_name)s started.',{'process_name':process_name})
    #~ logger.log(25,'Bots %(process_name)s configdir: "%(configdir)s".',{'process_name':process_name,'configdir':botsglobal.ini.get('directories','config')})
    port = 28082  # botsglobal.ini.getint('jobqueue','port',28082)
    #~ logger.log(25,'Bots %(process_name)s listens for xmlrpc at port: "%(port)s".',{'process_name':process_name,'port':port})

    #start launcher thread
    lauchfrequency = 5  # botsglobal.ini.getint('jobqueue','lauchfrequency',5)
    maxruntime = 60  # botsglobal.ini.getint('settings','maxruntime',60)
    for thread in range(nr_threads)
        launcher_thread = threading.Thread(name='launcher', target=launcher,
                                           args=(logger, queue, lauchfrequency, maxruntime))
        launcher_thread.start()
        #~ logger.info('Jobqueue launcher started.')

    #the main thread is the xmlrpc server: all adding, getting etc for jobqueue is done via xmlrpc.
    #~ logger.info('Jobqueue server started.')
    server = SimpleXMLRPCServer(('localhost', port), logRequests=False)
    server.register_instance(Jobqueue(logger))
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass

    sys.exit(0)
示例#21
0
    def test_exposeLambda(self):
        """Expose a lambda function via XML-RPC."""
        # Create a server instance.
        server = SimpleXMLRPCServer((HOST, PORT))
        server.register_function(lambda x, y: x+y, 'add')
        ServerThread(server).start()

        # Access the exposed service.
        client = xmlrpc.client.ServerProxy("http://%s:%d" % (HOST, PORT))
        self.assertEqual(client.add(10, 20), 30)
示例#22
0
def serve_player(player, address, port):
    """Serve player on specified bind address and port number."""
    from xmlrpc.server import SimpleXMLRPCServer
    server = SimpleXMLRPCServer((address, port))
    server.register_instance(player)
    print("Listening on " + address + ":" + str(port))
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
示例#23
0
def serve_agent(agent, address, port):
    """Serve agent on specified bind address and port number."""
    from xmlrpc.server import SimpleXMLRPCServer
    server = SimpleXMLRPCServer((address, port), allow_none=True)
    server.register_instance(agent)
    print("Listening on ", address, ":", port, sep="")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
示例#24
0
def main():
    # Parse CLI options
    import argparse
    cli_parser = argparse.ArgumentParser(
        description="XML-RPC server for filtering recommendations."
        )

    # Add verbosity option
    cli_parser.add_argument('-v', '--verbose', action='store_true',
                            help='Be more verbose')
    args = cli_parser.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.INFO)

    profiler = EditProfiler()
    server = SimpleXMLRPCServer(
        (config.edit_server_hostname, config.edit_server_hostport),
        allow_none=True)

    server.register_introspection_functions()
    server.register_function(profiler.get_edits, 'get_edits')
    server.register_function(profiler.make_profile, 'make_profile')
    print("Edit profiler is running...")

    # Run the server's main loop
    server.serve_forever()
示例#25
0
def main():
    """ Parse argument list and execute command. """

    global CONNECTION
    global SERVER
    global HEADERS
    global XMLRPC_URL
    global TENANT_ID

    usage = "%s [options]" % sys.argv[0]

    parser = ArgumentParser(usage=usage)

    parser.add_argument("-x", "--xmlrpc", dest="xmlrpc",
                        default="http://127.0.0.1:8000/RPC2",
                        help="Specify the XML-RPC server URL")

    parser.add_argument("-a", "--hostname", dest="host", default="127.0.0.1",
                        help="EmPOWER REST address; default='127.0.0.1'")

    parser.add_argument("-p", "--port", dest="port", default="8888",
                        help="EmPOWER REST port; default=8888")

    parser.add_argument("-u", "--user", dest="user", default="root",
                        help="EmPOWER admin user; default='root'")

    parser.add_argument("-n", "--no-passwd", action="store_true",
                        dest="no_passwd", default=False,
                        help="Run without password; default false")

    parser.add_argument("-f", "--passwd-file", dest="passwdfile",
                        default=None, help="Password file; default=none")

    parser.add_argument("-i", "--tenant-id", dest="tenant_id",
                        default=None, help="Tenant id; default=none")

    parser.add_argument("-t", "--transport", dest="transport", default="http",
                        help="Specify the transport; default='http'")

    (args, _) = parser.parse_known_args(sys.argv[1:])

    CONNECTION, HEADERS = get_connection(args)

    SERVER = SimpleXMLRPCServer(("localhost", 8000))
    XMLRPC_URL = args.xmlrpc
    TENANT_ID = args.tenant_id

    # synch state
    synch_callback(url='/api/v1/tenants/%s/cppup' % args.tenant_id)

    # register callback
    cpp_up(callback=cpp_up_callback)

    # Start xml-rpc server
    SERVER.serve_forever()
示例#26
0
 def __init__(
     self,
     addr,
     log=None,
     requestHandler=SAMPSimpleXMLRPCRequestHandler,
     logRequests=True,
     allow_none=True,
     encoding=None,
 ):
     self.log = log
     SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, allow_none, encoding)
示例#27
0
    def __init__(self, bind_address, bind_port=61209,
                 requestHandler=GlancesXMLRPCHandler):

        try:
            self.address_family = socket.getaddrinfo(bind_address, bind_port)[0][0]
        except socket.error as e:
            logger.error("Couldn't open socket: {0}".format(e))
            sys.exit(1)

        SimpleXMLRPCServer.__init__(self, (bind_address, bind_port),
                                    requestHandler)
示例#28
0
 def __init__(self, *args, **kwargs):
     class AuthRequestHandler(SimpleXMLRPCRequestHandler):
         def parse_request(myself):
             if SimpleXMLRPCRequestHandler.parse_request(myself):
                 if self.authenticate(myself.headers):
                     return True
                 else:
                     myself.send_error(401, "Authentication failure")
                     return False
     SimpleXMLRPCServer.__init__(self, requestHandler=AuthRequestHandler,
                                 *args, **kwargs
                                 )
示例#29
0
def main():
    host = "localhost"
    port = 7500

    data_handler = DatabaseHandler()
    
    try:
        server = SimpleXMLRPCServer((host, port))
        server.register_instance(data_handler)
        server.serve_forever()
    except KeyboardInterrupt:
        print("Caught control-c, closing database connection")
        data_handler.close()
 def _start(self):
     '''
     Start the server part of client.
     '''
     global PORT
     global ADDRESS
     try:
         server = SimpleXMLRPCServer((ADDRESS, PORT))
         server.register_instance(self)
         server.serve_forever()
     except:
         PORT+=1
         self._start()
示例#31
0
    def __init__(self, direccion):
        self._datos = {}
        self._servidor = SimpleXMLRPCServer(direccion, allow_none=True)

        for metodo in self._metodos_rpc:
            self._servidor.register_function(getattr(self, metodo))
示例#32
0
class RPCServer(object):
    """
    An aynchronous RPC server.
    """
    def __init__(self, port, context):
        self.__running = False
        logging.info('Setting up an RPC server on port %d', port)
        self.__server = SimpleXMLRPCServer(("localhost", port), logRequests=False, allow_none=True)
        self.__server.register_function(context['api']['show_settings'], 'show_settings')
        self.__server.register_function(context['api']['show_about'], 'show_about')
        self.__server.register_function(context['api']['enable_safeeyes'], 'enable_safeeyes')
        self.__server.register_function(context['api']['disable_safeeyes'], 'disable_safeeyes')
        self.__server.register_function(context['api']['take_break'], 'take_break')
        self.__server.register_function(context['api']['quit'], 'quit')

    def start(self):
        """
        Start the RPC server.
        """
        if not self.__running:
            self.__running = True
            logging.info('Start the RPC server')
            server_thread = Thread(target=self.__server.serve_forever)
            server_thread.start()

    def stop(self):
        """
        Stop the server.
        """
        if self.__running:
            logging.info('Stop the RPC server')
            self.__running = False
            self.__server.shutdown()
示例#33
0
# import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCServer

# import SimpleXMLRPCRequestHandler
from xmlrpc.server import SimpleXMLRPCRequestHandler
import threading


# Batasi hanya pada path /RPC2 saja supaya tidak bisa mengakses path lainnya
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

# Buat server
with SimpleXMLRPCServer(("192.168.43.122", 54321),
                        requestHandler=RequestHandler, allow_none=True) as server:
    server.register_introspection_functions()

    # buat data struktur dictionary untuk menampung nama_kandidat dan hasil voting
    kandidat = {'candidate_1': 0, 'candidate_2': 0}

    # kode setelah ini adalah critical section, menambahkan vote tidak boeh terjadi race condition
    # siapkan lock
    lock = threading.Lock()

    #  buat fungsi bernama vote_candidate()
    def vote_candidate(nama):

        # critical section dimulai harus dilock
        lock.acquire()
        # jika kandidat ada dalam dictionary maka tambahkan  nilai votenya
        if kandidat.get(nama) != None:
示例#34
0
 def serverStart(self):
     self.server = SimpleXMLRPCServer((self.host, self.portno))
     self.createProxy()
     print("Listening on port " + str(self.portno) + " ...")
     self.server.handle_request()
示例#35
0
# Read configuration file
def get_conf(filename):
    with open(filename, "r") as file:
        line = file.readline().split(',')
        return line

server, port = get_conf('server.conf')


# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)


# Create server
server = SimpleXMLRPCServer((server, int(port)),
                            requestHandler=RequestHandler)
server.register_introspection_functions()


# Just for testing
def adder_function(x,y):
    return x + y
server.register_function(adder_function, 'add')


# Matrix multiplication
def mmul(array):
    print("Matrix multiplication called")
    work = np.array(array)
    result = np.matmul(array, array)
示例#36
0
 def startTCPServer(self):
     self.server = SimpleXMLRPCServer(("data.cs.purdue.edu", self.portno))
示例#37
0
    def run(self):
        global RUNNING
        RUNNING = True

        ### server handling all other functions than stop functions.
        try:
            server = SimpleXMLRPCServer(
                (conf.NOVO_daemon_host, conf.NOVO_daemon_port1),
                requestHandler=RequestHandler,
                logRequests=False,
                allow_none=True)
            server.allow_reuse_address = True
        except Exception as e:
            print('error: ', e)

        ### server handling the stop functions. This is to being able to send stop commands while the "while-loops" are running.
        try:
            server2 = SimpleXMLRPCServer(
                (conf.NOVO_daemon_host, conf.NOVO_daemon_port2),
                requestHandler=RequestHandler,
                logRequests=False,
                allow_none=True)
            server2.allow_reuse_address = True
        except Exception as e:
            print('error:', e)

        ###################################################
        #Setting a handle for the PWI2-class in PW_Class.py.
        #This makes it possible for the server to call the correct functions in PWI2

        PWI = PW.PWI4()

        ###################################################
        # I define all the functions in PWI as a new function that the server can call them

        def Initialize():
            PWI.__init__()
            return

        def ConnectMNT():
            cmd = PWI.ConnectMNT()
            return cmd

        def ConnectFOC():
            cmd = PWI.ConnectFOC()
            return cmd

        def DisconnectFOC():
            cmd = PWI.DisconnectFOC()
            return cmd

        def DisconnectMNT():
            cmd = PWI.DisconnectMNT()
            return cmd

        def getStatus():
            cmd = PWI.getStatus()
            return cmd

        def setTargetRaDecJ2000(RA, DEC):
            cmd = PWI.setTargetRaDecJ2000(RA, DEC)
            return cmd

        def setTargetAltAzm(Alt, Azm):
            cmd = PWI.setTargetAltAzm(Alt, Azm)
            return cmd

        def setTargetRaDec(RA, DEC):
            cmd = PWI.setTargetRaDec(RA, DEC)
            return cmd

        def MntMoveRaDecJ2000():
            cmd = PWI.MntMoveRaDecJ2000()
            return cmd

        def update():
            reply = PWI.update()
            return reply

        def getALL():
            reply = PWI.getALL()
            return reply

        def getRA2000():
            reply = PWI.getRA2000()
            return reply

        def getDEC2000():
            reply = PWI.getDEC2000()
            return reply

        def getFocuserPos():
            reply = PWI.getFocuserPos()
            return reply

        def getMNT_CONNECT():
            reply = PWI.getMNT_CONNECT()
            return reply

        def getFOC_CONNECT():
            reply = PWI.getFOC_CONNECT()
            return reply

        def getROT_CONNECT():
            reply = PWI.getROT_CONNECT()
            return reply

        def getIsTrackingOn():
            reply = PWI.getIsTrackingOn()
            return reply

        def getTemps():
            reply = PWI.getTemps()
            return reply

        def getRotatorDerotate():
            reply = PWI.getRotatorDerotate()
            return reply

        def MoveFocuserPos(position):
            reply = PWI.MoveFocuserPos(position)
            return reply

        def FocSTOP():
            reply = PWI.FocSTOP()
            return reply

        def MntMotorReset():
            reply = PWI.MntMotorReset()
            return reply

        def checkFormatRaDec(Ra, Dec):
            PWI.checkFormatRaDec(Ra, Dec)
            return

        def checkFormatAltAzm(Alt, Azm):
            PWI.checkFormatAltAzm(Alt, Azm)
            return

        def checkFormatArcsec(Arcsec):
            PWI.checkFormatArcsec(Arcsec)
            return

        def stopTracking():
            reply = PWI.stopTracking()
            return reply

        def parkMount():
            reply = PWI.parkMount()
            return reply

        def getRotatorPos():
            reply = PWI.getRotatorPos()
            return reply

        def MountSTOP():
            reply = PWI.MountSTOP()
            return reply

        def MntMotorEnable():
            reply = PWI.MntMotorEnable()
            return reply

        def MntMotorDisable():
            reply = PWI.MntMotorDisable()
            return reply

        def MntMoveRaDec():
            reply = PWI.MntMoveRaDec()
            return reply

        def MntMoveAltAzm():
            reply = PWI.MntMoveAltAzm()
            return reply

        def startTracking():
            reply = PWI.startTracking()
            return reply

        def LoadPointingModel(filename):
            reply = PWI.LoadPointingModel(filename)
            return reply

        def AddPointToModel(Ra, Dec):
            cmd = PWI.AddPointToModel(Ra, Dec)
            return cmd

        def SavePointingModel(filename):
            cmd = PWI.SavePointingModel(filename)
            return cmd

        def ClearPointingModel():
            reply = PWI.ClearPointingModel()
            return reply

        def FansON():
            reply = PWI.FansON()
            return reply

        def FansOFF():
            reply = PWI.FansOFF()
            return reply

        def Rot_Move(position):
            reply = PWI.Rot_Move(position)
            return reply

        def RotSTOP():
            reply = PWI.RotSTOP()
            return reply

        def Rot_derotateStart():
            reply = PWI.Rot_derotateStart()
            return reply

        def Rot_derotateStop():
            reply = PWI.Rot_derotateStop()
            return reply

        def getTrackingRMSError():
            reply = PWI.getTrackingRMSError()
            return reply

        def startMntHoming():
            reply = PWI.startMntHoming()
            return reply

        ########################################################################## register functions for server2 - handling stop commands
        server2.register_function(FocSTOP)
        server2.register_function(MountSTOP)
        server2.register_function(RotSTOP)
        server2.register_function(stop_server)

        ##################################################################### register functions for server - operational commands
        server.register_function(DisconnectMNT)
        server.register_function(DisconnectFOC)
        server.register_function(ConnectFOC)
        server.register_function(ConnectMNT)
        server.register_function(Initialize)
        server.register_function(getStatus)
        server.register_function(MntMoveRaDecJ2000)
        server.register_function(update)
        server.register_function(getALL)
        server.register_function(getRA2000)
        server.register_function(getDEC2000)
        server.register_function(getFocuserPos)
        server.register_function(getMNT_CONNECT)
        server.register_function(getFOC_CONNECT)
        server.register_function(getROT_CONNECT)
        server.register_function(getIsTrackingOn)
        server.register_function(getTemps)
        server.register_function(MoveFocuserPos)
        server.register_function(MntMotorReset)
        server.register_function(checkFormatRaDec)
        server.register_function(checkFormatAltAzm)
        server.register_function(checkFormatArcsec)
        server.register_function(stopTracking)
        server.register_function(parkMount)
        server.register_function(MntMotorEnable)
        server.register_function(MntMotorDisable)
        server.register_function(MntMoveRaDec)
        server.register_function(MntMoveAltAzm)
        server.register_function(startTracking)
        server.register_function(LoadPointingModel)
        server.register_function(AddPointToModel)
        server.register_function(SavePointingModel)
        server.register_function(ClearPointingModel)
        server.register_function(FansON)
        server.register_function(FansOFF)
        server.register_function(Rot_Move)
        server.register_function(Rot_derotateStart)
        server.register_function(Rot_derotateStop)
        server.register_function(setTargetRaDecJ2000)
        server.register_function(setTargetAltAzm)
        server.register_function(setTargetRaDec)
        server.register_function(getRotatorPos)
        server.register_function(getRotatorDerotate)
        server.register_function(getTrackingRMSError)
        server.register_function(startMntHoming)

        server.register_function(stop_server)

        #####################################################################

        #Threading the two servers such that they run on their individual thread.
        def server2thread():
            while RUNNING:
                server2.handle_request()

        thread_value = _thread.start_new_thread(server2thread, ())
        print('Thread successful')
        #server2thread()

        #The server starts taking requests
        print("Starting handle_request loop...")
        while RUNNING:
            server.handle_request()
示例#38
0
    cont_params.Ki = 0
    cont_params.Delay1 = 0
    cont_params.Delay2 = 0
    cont_params.Offset = 0
    return


# Launch the server. The rest of the code is essentially copy&pasted
# Restrict to a particular path
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2', )


# Create server, use RedPitayas IP
server = SimpleXMLRPCServer(("130.183.94.184", 8000),
                            requestHandler=RequestHandler,
                            allow_none=True)
server.register_introspection_functions()

# Register the functions defined above so they can be called by client
server.register_function(pg_set_values)
server.register_function(cont_reset)
server.register_function(pg_get_values)

try:
    print("Server started")
    print('Use Control-C to exit')
    server.serve_forever()  #Enter server main loop
except KeyboardInterrupt:
    print('Exiting')
    cont_reset()
示例#39
0
    def __init__(self, address):
        self._data = {}
        self.server = SimpleXMLRPCServer(address, allow_none=True)

        for name in self._rpc_methods_:
            self.server.register_function(getattr(self, name))
示例#40
0
    fecha_inicial = datetime.strptime(fecha, formato_fecha)
    hoy = datetime.now()
    edad = (hoy - fecha_inicial).days / 365
    edad = int(edad)
    nombre = nombre
    print('formulario recibido: ', nombre, apellido, ci, f_n, lugar)

    with open("fetched_foto.png", "wb") as handle:
        handle.write(foto.data)
        tam = len(foto.data)

    respuesta = 'hola %s, edad: %s a#os' % (nombre, edad)
    print('foto revibida: ', tam, 'bytes')
    return respuesta


def python_logo():
    aleatorio = random.randint(0, 5)
    avatar = 'media/' + list_avatar[aleatorio] + '.png'
    print('enviando avatar...')
    with open(avatar, "rb") as handle:
        return xmlrpc.client.Binary(handle.read())


# A simple server with simple arithmetic functions
server = SimpleXMLRPCServer(("localhost", 8000))
print("escuchando port 8000...")

server.register_function(serverForm, 'formulario')
server.register_function(python_logo, 'foto')
server.serve_forever()
示例#41
0
 def _start(self):
     """用于启动XML_PRC服务器"""
     s = SimpleXMLRPCServer(("", getPort(self.url)), logRequests=True)
     s.register_instance(self)
     s.serve_forever()
示例#42
0
def rpc_server_main(sim_mode, addr=default_addr, port=default_port):
    global remote_controller
    if addr != default_addr:
        raise NotImplementedError
    if port != default_port:
        raise NotImplementedError
    remote_controller = vent.controller.control_module.get_control_module(sim_mode)
    server = SimpleXMLRPCServer((addr, port), allow_none=True, logRequests=False)
    server.register_function(get_sensors, "get_sensors")
    server.register_function(get_active_alarms, "get_active_alarms")
    server.register_function(get_logged_alarms, "get_logged_alarms")
    server.register_function(set_control, "set_control")
    server.register_function(get_control, "get_control")
    server.register_function(remote_controller.start, "start")
    server.register_function(remote_controller.is_running, "is_running")
    server.register_function(remote_controller.stop, "stop")
    server.serve_forever()
import struct
import socket
from xmlrpc.server import SimpleXMLRPCServer
from threading import Thread
import concurrent.futures
import proxy
import datetime
import json
import time

naming_proxy = proxy.TupleSpaceAdapter('http://localhost:8004')


MAX_UDP_PAYLOAD = 65507

server = SimpleXMLRPCServer(("localhost", 5000), allow_none = True)
map_tuple_uri = {}
ack_track = {}

def replicate_tuple_to_all(name, data): # method to replicate the data to every node in teh cluster
    global map_tuple_uri, ack_track
    for key, val in map_tuple_uri.items():
        if key != name:
            replicate_proxy = proxy.TupleSpaceAdapter(val[0])
            replicate_proxy._out(data)

    return "Sucessfully replicated\n"

def delete_from_file(data): #helper to delete the data from the file
    with open("log_data.txt","r+") as f:
        new_f = f.readlines()
示例#44
0
class Servidor(QtGui.QMainWindow):
    def __init__(self):
        super(Servidor, self).__init__()
        uic.loadUi('servidor.ui', self)
        self.terminar.hide()
        self.iniciar = False
        self.pausar = False
        self.timer = 0
        timer_s = None
        timer_camino = None
        self.vivoras = []
        self.agrandar_cuadros()
        self.llenar_tabla()
        self.pushButton.clicked.connect(self.inicializa)
        self.tableWidget.setSelectionMode(QtGui.QTableWidget.NoSelection)
        self.spinBox_2.valueChanged.connect(self.actualiza_tabla)
        self.spinBox_3.valueChanged.connect(self.actualiza_tabla)
        self.spinBox.valueChanged.connect(self.actualizar_timer)
        self.iniciar_pausar.clicked.connect(self.comenzar_juego)
        self.terminar.clicked.connect(self.terminar_juego)
        self.show()

    def aux(self):
        self.servidor.handle_request()

    def nuevo_camino(self):
        for vivora in self.vivoras:
            vivora.camino = []
            for celda in vivora.casillas:
                vivora.camino.append((celda[0], celda[1]))

    def inicializa(self):
        puerto = self.h.value()
        direccion = self.lineEdit.text()
        print(puerto)
        self.servidor = SimpleXMLRPCServer((direccion, 0))
        puerto2 = self.servidor.server_address[1]
        print(puerto2)
        self.h.setValue(puerto2)
        self.pushButton.setText(str(puerto2))
        self.h.setReadOnly(True)
        self.lineEdit.setReadOnly(True)
        self.pushButton.setEnabled(False)
        self.servidor.register_function(self.ping)
        self.servidor.register_function(self.yo_juego)
        self.servidor.register_function(self.cambia_direccion)
        self.servidor.register_function(self.estado_del_juego)
        self.servidor.timeout = 0
        self.timer_s = QtCore.QTimer(self)
        self.timer_s.timeout.connect(self.aux)
        self.timer_s.start(self.servidor.timeout)

    def hacer_server(self):
        self.pushButton.setText("hola")

    def lista_de_jugadores(self):
        lista = []
        for vivora in self.vivoras:
            lista.append(vivora.dicionario())
        return lista

    def ping(self):
        return "¡Pong!"

    def yo_juego(self):
        nueva_vivora = self.nueva_vivora()
        diccionario = {
            "id": serpiente_nueva.id,
            "color": serpiente_nueva.color
        }
        return diccionario

    def cambia_direccion(self):
        for s in self.vivoras:
            if s.id == identificador:
                if numero == 0:
                    if s.direccion is not "Abajo":
                        s.direccion = "Arriba"
                if numero == 1:
                    if s.direccion is not "Izquierda":
                        s.direccion = "Derecha"
                if numero == 2:
                    if s.direccion is not "Arriba":
                        s.direccion = "Abajo"
                if numero == 3:
                    if s.direccion is not "Derecha":
                        s.direccion = "Izquierda"
        return True

    def estado_del_juego(self):
        diccionario = dict()
        diccionario = {
            'espera': self.servidor.timeout,
            'tamX': self.tableWidget.columnCount(),
            'tamY': self.tableWidget.rowCount(),
            'viboras': self.lista_de_jugadores()
        }
        return diccionario

    def crear_vivora(self):
        vivora_nueva = Vivora()
        creada = False
        while not creada:
            creada = True
            uno = randint(1, self.tableWidget.rowCount() / 2)
            dos = uno + 1
            tres = dos + 1
            ancho = randint(1, self.tableWidget.columnCount() - 1)
            achecar_1, achecar_2, achecar_3 = [uno,
                                               ancho], [dos,
                                                        ancho], [tres, ancho]
            for s in self.vivoras:
                if achecar_1 in s.casillas or achecar_2 in s.casillas or achecar_3 in s.casillas:
                    creada = False
                    break
            vivora_nueva.casillas = [achecar_1, achecar_2, achecar_3]
            self.vivoras.append(vivora_nueva)
            return vivora_nueva

    def actualiza_timer2(self):
        self.servidor.timeout = self.time.value()
        self.timer_s.setInterval(self.time.value())

    def comenzar_juego(self):
        if not self.iniciar:
            self.terminar.show()
            self.crear_vivora()
            self.iniciar_pausar.setText("Pausar Juego")
            self.dibujar_vivoras()
            self.timer = QtCore.QTimer(self)
            self.timer.timeout.connect(self.mover_vivoras)
            self.timer.start(100)
            self.tableWidget.installEventFilter(self)
            self.timer_camino = QtCore.QTimer(self)
            self.timer_camino.timeout.connect(self.nuevo_camino)
            self.timer_camino.start(100)
            self.tableWidget.installEventFilter(self)
            self.iniciar = True
        elif self.iniciar and self.pausar == False:
            self.timer.stop()
            self.pausar = True
            self.iniciar_pausar.setText("Reanudar el Juego")
        elif self.pausar:
            self.timer.start()
            self.pausar = False
            self.iniciar_pausar.setText("Pausar Juego")

    def terminar_juego(self):
        self.vivoras = []
        self.timer.stop()
        self.iniciar = False
        self.terminar.hide()
        self.iniciar_pausar.setText("Iniciar Juego")
        self.llenar_tabla()

    def actualizar_timer(self):
        valor = self.spinBox.value()
        self.timer.setInterval(valor)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.KeyPress
                and source is self.tableWidget):
            key = event.key()
            if (key == QtCore.Qt.Key_Up and source is self.tableWidget):
                for vivora in self.vivoras:
                    if vivora.direccion is not "Abajo":
                        vivora.direccion = "Arriba"
            elif (key == QtCore.Qt.Key_Down and source is self.tableWidget):
                for vivora in self.vivoras:
                    if vivora.direccion is not "Arriba":
                        vivora.direccion = "Abajo"
            elif (key == QtCore.Qt.Key_Right and source is self.tableWidget):
                for vivora in self.vivoras:
                    if vivora.direccion is not "Izquierda":
                        vivora.direccion = "Derecha"
            elif (key == QtCore.Qt.Key_Left and source is self.tableWidget):
                for vivora in self.vivoras:
                    if vivora.direccion is not "Derecha":
                        vivora.direccion = "Izquierda"
        return QtGui.QMainWindow.eventFilter(self, source, event)

    def dibujar_vivoras(self):
        for vivora in self.vivoras:
            for parte_vivora in vivora.casillas:
                self.tableWidget.item(parte_vivora[0],
                                      parte_vivora[1]).setBackground(
                                          QtGui.QColor(vivora.color['r'],
                                                       vivora.color['g'],
                                                       vivora.color['b']))

    def se_comio(self, vivora):
        for parte_de_vivora in vivora.casillas[0:len(vivora.casillas) - 2]:
            if vivora.casillas[-1][0] == parte_de_vivora[
                    0] and vivora.casillas[-1][1] == parte_de_vivora[1]:
                return True
        return False

    def choca_con_otra_vivora(self, revisar):
        for vivora in self.vivoras:
            if vivora.id != revisar.id:
                for parte_cuerpo in vivora.casillas[:]:
                    if revisar.casillas[-1][0] == parte_cuerpo[
                            0] and revisar.casillas[-1][1] == parte_cuerpo[1]:
                        self.serpientes_juego.remove(serpiente_a_checar)

    def mover_vivoras(self):
        for vivora in self.vivoras:
            if self.se_comio(vivora) or self.choca_con_otra_vivora(vivora):
                self.vivoras.remove(vivora)
                self.llenar_tabla()
                vivora_1 = self.crear_vivora()
                self.vivoras = [vivora_1]
            self.tableWidget.item(vivora.casillas[0][0],
                                  vivora.casillas[0][1]).setBackground(
                                      QtGui.QColor(82, 130, 135))
            x = 0
            for tupla in vivora.casillas[0:len(vivora.casillas) - 1]:
                x += 1
                tupla[0] = vivora.casillas[x][0]
                tupla[1] = vivora.casillas[x][1]
            if vivora.direccion == "Abajo":
                if vivora.casillas[-1][0] + 1 - self.tableWidget.rowCount(
                ) < 0:
                    vivora.casillas[-1][0] += 1
                else:
                    vivora.casillas[-1][0] = 0
            if vivora.direccion == "Derecha":
                if vivora.casillas[-1][1] + 1 - self.tableWidget.columnCount(
                ) < 0:
                    vivora.casillas[-1][1] += 1
                else:
                    vivora.casillas[-1][1] = 0
            if vivora.direccion == "Arriba":
                if vivora.casillas[-1][0] != 0: vivora.casillas[-1][0] -= 1
                else:
                    vivora.casillas[-1][0] = self.tableWidget.rowCount() - 1
            if vivora.direccion == "Izquierda":
                if vivora.casillas[-1][1] != 0: vivora.casillas[-1][1] -= 1
                else:
                    vivora.casillas[-1][1] = self.tableWidget.columnCount() - 1
        self.dibujar_vivoras()

    def llenar_tabla(self):
        for i in range(self.tableWidget.rowCount()):
            for j in range(self.tableWidget.columnCount()):
                self.tableWidget.setItem(i, j, QtGui.QTableWidgetItem())
                self.tableWidget.item(i, j).setBackground(
                    QtGui.QColor(80, 134, 134))

    def agrandar_cuadros(self):
        self.tableWidget.horizontalHeader().setResizeMode(
            QtGui.QHeaderView.Stretch)
        self.tableWidget.verticalHeader().setResizeMode(
            QtGui.QHeaderView.Stretch)

    def actualiza_tabla(self):
        filas = self.spinBox_2.value()
        columnas = self.spinBox_3.value()
        self.tableWidget.setRowCount(filas)
        self.tableWidget.setColumnCount(columnas)
        self.llenar_tabla()
示例#45
0
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
import os
import shutil


class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2', )


with SimpleXMLRPCServer(('192.168.1.64', 56432),
                        requestHandler=RequestHandler) as Server:
    Server.register_introspection_functions()

    def CREATE(name):
        try:
            with open(name, "x") as file:
                return name + " Creado correctamente"
                print()
        except FileExistsError:
            return "¡¡Archivo existente!!"
        except FileNotFoundError:
            return "¡¡Ruta no existente!!"

    Server.register_function(CREATE)

    def READ(name):
        try:
            with open(name, "r") as file:
                return file.read()
                print()
示例#46
0
        'WXCheck',
    ]
    # Assemble
    params = (binscope_path + target + out_type + output + checks)

    # Execute process
    p = subprocess.Popen(subprocess.list2cmdline(params))
    p.wait()  # Wait for the process to finish..

    # Open the file and return the json
    f = open(output[1])
    return f.read()


if __name__ == '__main__':
    # Init configparser
    config = configparser.ConfigParser()

    config.read(expanduser('~') + '\\MobSF\\Config\\config.txt')

    _init_key()

    server = SimpleXMLRPCServer(('0.0.0.0', 8000))
    print('Listening on port 8000...')
    server.register_function(get_challenge, 'get_challenge')
    server.register_function(test_challenge, 'test_challenge')
    server.register_function(upload_file, 'upload_file')
    server.register_function(binskim, 'binskim')
    server.register_function(binscope, 'binscope')
    server.serve_forever()
示例#47
0
# gunakan xmlrpc bagian server
# import SimpleXMLRPCServer dan SimpleXMLRPCRequestHandler
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

# buat kelas requesthandler
# batasi pada path /RPC2 saja


class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2', )


# buat server serta register fungsi register_introspection_functions()
with SimpleXMLRPCServer(("127.0.0.1", 8008),
                        requestHandler=RequestHandler) as server:
    server.register_introspection_functions()

    # cara 1 untuk memasukkan fungsi dalam server adalah dengan langsung memasukkan namanya
    # fungsi pow() merupakan fungsi build in pada pyhton, tinggal dipanggil saja
    server.register_function(pow)

    # cara 2 untuk register fungsi: buat fungsinya kemudian register
    # a. buat fungsi
    def adder_function(x, y):
        return x + y

    # b. register fungsinya
    server.register_function(adder_function, 'add')

    # cara 3: tidak hanya fungsi, class juga bisa diregisterkan
示例#48
0
        e.g. return until keyframes are executed
        '''
        # YOUR CODE HERE
        self.keyframes = keyframes
        while self.keyframes != ([], [], []):
            time.sleep(0.01)
        return True


    def get_transform(self, name):
        '''get transform with given name
        '''
        # YOUR CODE HERE
        return self.transforms[name]

    def set_transform(self, effector_name, transform):
        '''solve the inverse kinematics and control joints use the results
        '''
        # YOUR CODE HERE
        raise NotImplemented

if __name__ == '__main__':
    with SimpleXMLRPCServer(('localhost', 8000)) as server:
        server.register_instance(ServerAgent(), allow_dotted_names=True)
        server.register_multicall_functions()
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            sys.exit(0)

示例#49
0
# import library yang dibutuhkan
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
import json

# Batasi hanya pada path /RPC2 saja supaya tidak bisa mengakses path lainnya


class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2', )


# Buat server
with SimpleXMLRPCServer(("localhost", 80),
                        requestHandler=RequestHandler) as server:
    server.register_introspection_functions()

    # membuat database untuk menerima inputan
    db = []
    # batas normal kadar gula darah
    threshold = 100

    # fungsi menentukan pasien sakit atau tidak
    def controlGula(nama, gula_darah):
        # inisialisasi data
        data = {
            'id': len(db) + 1,
            'nama': nama,
            'gula_darah': int(gula_darah),
            'status': False,
            'danger': False,
from xmlrpc.server import SimpleXMLRPCServer
from datetime import datetime


def get_time():
    return datetime.isoformat(datetime.now())


server = SimpleXMLRPCServer(("localhost", 6789))
server.register_function(get_time, "get_time")
server.serve_forever()
示例#51
0
def open_rpc_server():
    address = ('localhost', 3333)
    server = SimpleXMLRPCServer(address)
    print('server started')
    server.register_function(savelog,"log")
    server.serve_forever()
示例#52
0
class TCPNode(Node):
    def __init__(self, id, object, type, port):
        super().__init__(id)
        self.portno = port
        self.type = type
        self.rname = filename.filename
        self.host = 'data.cs.purdue.edu'
        self.object = object

    def reader(self):
        return self.object

    def createProxy(self):
        self.server.register_function(self.reader, 'reader')

    def serverStart(self):
        self.server = SimpleXMLRPCServer((self.host, self.portno))
        self.createProxy()
        print("Listening on port " + str(self.portno) + " ...")
        self.server.handle_request()

    '''
        Turn on (deploy) the node.
    '''

    def start(self):
        super().start()

    def startTCPServer(self):
        self.server = SimpleXMLRPCServer(("data.cs.purdue.edu", self.portno))
        # self.createProxy()
        # print("Listening on port "+str(self.portno)+" ...")
        # self.server.handle_request()

    def startTCPClient(self):
        self.proxy = xmlrpc.client.ServerProxy("http://" + self.host + ":" +
                                               str(self.portno) + "/")

    '''
        Turn off (undeploy) the node.
    '''

    def stop(self, disconnect=True):
        super().stop()

    '''
        Connect an undeployed node to this one directly through memory.
        If duplex is true, the given node will also be connected to this one.
    '''

    def connectTCP(
            self, node
    ):  #TODO: add code to connect to a remote TCPNode at host:port.
        self._connectConn(node)

        #      Store info in self.conns dict to map the id to the connection object.
        #      Make sure you can internally distinguish between tcp and local conns.

    def _connectConn(self, node):
        connRec = self._buildConnRec(node)
        self.conns[node.id] = connRec

    def _buildConnRec(self, node):
        connRec = dict()
        connRec["line"] = node.inputLine
        connRec["type"] = node.type
        return connRec

    def send(self, id, msg):
        self._checkNodeOn()
        try:
            connRec = self.conns[id]
            self._send(connRec, msg)
        except KeyError:
            raise ValueError("[ProcNode]: Error. ID %s not found." % str(id))

    def _send(self, connRec, msg):
        if connRec["type"] == "TCP":
            self.object = msg
            self.createProxy()
            print("Listening on port " + str(self.portno) + " ...")
            self.server.handle_request()

        else:
            connRec["line"].put(msg)

    '''
        Turn a present connection into a duplex.
    '''

    def duplexify(
            self, id
    ):  #TODO: All tcp conns are duplexes, so check if id is a tcp node.
        raise NotImplementedError  #      If so, ignore the call. else, call super version.
        super().duplexify(id)

    '''
        Disconnect the node from node1 with given id.
        If notify is true, node1 will be instructed to disconnect from this node too.
    '''

    def disconnect(
        self,
        id,
        notify=True
    ):  #TODO: If id is a tcp node, disconnect in your own way. else, call super version.
        raise NotImplementedError
        super().disconnect(id, notify=notify)

    '''
        Quickly handle all updates on the inputLine.
        Node msgs are relocated to the msgQueue.
    '''

    def update(self):  #TODO: Implement for super version and tcp nodes.
        raise NotImplementedError
        super().update()

    '''
        Send a node msg to the node indexed by id.
        If the id is not connected, raise a ValueError.
    '''
    # def send(self, id, msg):                                                    #TODO: Implement for super version and tcp nodes.
    #     raise NotImplementedError
    #     super().send(id, msg)
    '''
        Gets a node msg.
        If block is true, recv will only return when a msg is found, but will continue to update internally.
        If block is false, recv will finish updating and either return a found msg or raise Empty.
    '''

    def recv(self,
             block=True):  #TODO: Implement for super version and tcp nodes.
        print("IN NODE :" + str(self.id))
        flag = 0
        if self.type == "TCP":
            self.proxy = xmlrpc.client.ServerProxy("http://" + self.host +
                                                   ":" + str(self.portno) +
                                                   "/")
            dictionary = self.proxy.reader()
            a1 = c1.CustomObject(**dictionary)
            print(a1.returnList())
            print(a1.returnStr())
            print(a1.returnDic())

        else:
            super().recv(block=block)


#===============================================================================
from xmlrpc.server import SimpleXMLRPCServer

def sub(n1, n2):
    return n1 - n2

server = SimpleXMLRPCServer(("localhost", 8002))
print("Listening on port 8002...")
server.register_function(sub, "sub")
server.serve_forever()
示例#54
0
from datetime import datetime
from xmlrpc.server import SimpleXMLRPCServer


def responz(wtisit):
    if wtisit == "What time is it?":
        return datetime.now().isoformat()


server = SimpleXMLRPCServer(("localhost", 5000))
server.register_function(responz)
server.serve_forever()
示例#55
0
from xmlrpc.server import SimpleXMLRPCServer
from multiprocessing import Process
import worker as w
from redis import Redis
import json

server = SimpleXMLRPCServer(("localhost", 8001), allow_none=True)
r = Redis()
server.register_introspection_functions()
WORKERS = {}
WORKER_ID = 0
TASK_ID = 0


#Create a worker
def create_worker():
    print("----------\nSERVER: CREATE_WORKER")
    global WORKERS
    global WORKER_ID
    proc = Process(target=w.start_worker, args=(
        WORKER_ID,
        r,
    ))
    proc.start()
    WORKERS[WORKER_ID] = proc
    WORKER_ID += 1


#Delete a worker
def delete_worker(id):
    print("----------\nSERVER: DELETE_WORKER")
示例#56
0
 def __init__(self,
              addr,
              request_handler=SilenceableXMLRPCRequestHandler,
              log_requests=1):
     SimpleXMLRPCServer.__init__(self, addr, request_handler, log_requests)
示例#57
0
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler


def peso_ideal(altura, sexo):
    if sexo == "masculino":
        return (72.7 * altura) - 58
    else:
        return (62.1 * altura) - 44.7


class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2', )


if __name__ == '__main__':
    HOST, PORT = "localhost", 9991

    # Tenta criar um serivdor TCP
    with SimpleXMLRPCServer((HOST, PORT), RequestHandler) as server:
        server.register_introspection_functions()

        server.register_function(peso_ideal)

        server.serve_forever()
示例#58
0
    timeout = args.timeout

    port_number = args.port_number
    server_url = '0.0.0.0'

    # if args.config:
    #     config = json.load(open(args.config))
    #     server_url = config['serverUrl']
    #     port_number = int(server_url.split(':')[-1])
    #     timeout = int(config['timeout'])

    print('=============== Server Settings:')
    print('Server URL: ', server_url)
    print('Port Number:', port_number)
    print('Num CPUs:', n_cpus)
    print('Timeout: {}s'.format(timeout))
    print()

    eval_server = DagEvalServer(n_cpus, timeout)

    server = SimpleXMLRPCServer((server_url, port_number))
    server.register_instance(eval_server)

    try:
        server.serve_forever()
    except Exception as e:
        stop_server = True
        server.kill_workers()
        print("ERROR: ", str(e))
        print(repr(e))
示例#59
0
 def __init__(self):
     threading.Thread.__init__(self)
     self._rpc_methods = ['get_access_token', 'update_access_token']
     self._serv = SimpleXMLRPCServer(('127.0.0.1', 9000), logRequests=True, allow_none=True)
     for name in self._rpc_methods:
         self._serv.register_function(getattr(self, name))
示例#60
0
        '--url',
        dest='url',
        help='Interoperability Server URL, example: http://10.10.130.10:80',
        required=True)
    parser.add_argument(
        '--username',
        dest='username',
        help='Interoperability Username, example: calpoly-broncos',
        required=True)
    parser.add_argument('--password',
                        dest='password',
                        help='Interoperability Password, example: 4597630144',
                        required=True)

    cmd_args = parser.parse_args()
    relay = RelayService(url=cmd_args.url,
                         username=cmd_args.username,
                         password=cmd_args.password)

    # sets up the local proxy server (here on port 9001)
    server = SimpleXMLRPCServer(('127.0.0.1', 9001),
                                logRequests=True,
                                allow_none=True)
    server.register_instance(relay)

    try:
        print('Use Control-C to exit')
        server.serve_forever()
    except KeyboardInterrupt:
        print('Exiting')