Пример #1
0
 def start_server(self, address, password):
     print("server waiting")
     listener = Listener()
     client = Client(address)
     client.send(listener.address)
     self._start_listener(listener)
     return listener.address
Пример #2
0
def broadcast_mic_data():
    # get the latest data from the audio server
    parameters = {
        "upper_limit": UPPER_LIMIT,
        "noise_threshold": NOISE_THRESHOLD,
        "min_quiet_time": MIN_QUIET_TIME,
        "min_noise_time": MIN_NOISE_TIME
    }
    try:
        conn = Client(AUDIO_SERVER_ADDRESS)
        conn.send(parameters)
        results = conn.recv()
        conn.close()
        # send results to all clients
        now = datetime.now()
        results['date_current'] = '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(
            dt=now)
        results['time_current'] = now.strftime("%I:%M:%S %p").lstrip('0')
        results['audio_plot'] = results['audio_plot'].tolist()
    except:
        for c in clients:
            c.close()

    for c in clients:
        c.write_message(results)
Пример #3
0
def notify_new_client(id,clients): 
    for client, client_info in clients.items():
        if not client == id:
            print "sending new client to", client
            conn = Client(address=client_info[0], authkey=client_info[1])
            conn.send(("new client", id))
            conn.close()
Пример #4
0
    def send(self, msg):
        #conn = Client((self.address, self.port), authkey=str(self.key))
        conn = Client((self.address, self.port))

        conn.send(json.dumps(msg))

        conn.close()
Пример #5
0
class Worker(object):

    def __init__(self, address, port, authkey=None):

        self.connection = Client((address, port), authkey=authkey)
        self.worker_id = self.connection.recv()

    def run(self):
        while True:

            task_data = self.connection.recv()
            if task_data is False:
                return

            result = self.do_task(task_data)
            self.connection.send((task_data, result))

    def log(self, *items):
        print "== Worker %s ==" % self.worker_id,
        for item in items:
            print item,
        print

    def do_task(self, data):
        raise NotImplementedError("A subclass must implement this.")
Пример #6
0
def get_json():
    #Get the current values
    c = Client(('localhost', 25000))
    c.send("get")
    now = c.recv()

    #Now we parse all the data out of the results!
    data = {}
    data["IN_Temp"] = now.In_Temp
    data["IN_Humid"] = now.In_Humid
    data["OUT_Temp"] = now.Out_Temp
    data["OUT_Humid"] = now.Out_Humid
    data["Out_Wind_Now"] = now.Out_Wind_Now
    data["OUT_Wind_Avg"] = now.Out_Wind_Avg
    data["OUT_Wind_Max"] = now.Out_Wind_Max
    data["OUT_Rain_Today"] = now.Out_Rain_Today
    data["OUT_Rain_Last_24h"] = now.Out_Rain_Last_24h
    data["OUT_Rain_Since_Reset"] = now.Out_Rain_Since_Reset
    data["ATTIC_Temp"] = now.Attic_Temp
    data["ATTIC_Humid"] = now.Attic_Humid
    data["NOW_URL"] = now.Now_URL
    data["NOW_Feel"] = now.Now_Feel
    data["NOW_Feel_High"] = now.Now_Feel_High
    data["NOW_Feel_Low"] = now.NOW_Feel_Low
    data["SYSTEM_CPU"] = now.System_CPU
    data["SYSTEM_RAM"] = now.System_RAM

    #Now return the json as a string
    return json.dumps(data)
Пример #7
0
class ConnectClient():
    address = None
    conn = None
    
    def __init__(self, ip = 'localhost', port = 7000):
        self.address = (ip, port)
        self.conn = Client(self.address)

    def __del__(self):
        self.conn.close()
    
    def register_module(self, process_file):
        """send and register a module in the server"""
        f = open(process_file, "rb")
        l = f.read()
        self.conn.send([0, l])
        f.close()

    def request_process(self, args):
        """request the server to do a process previously sent in a module"""
        self.conn.send([1, args[0]] + args[1:])
        answer = self.conn.recv()
        if isinstance(answer, Exception):
            raise answer
        return answer
Пример #8
0
def communicate(message):
    address = ('localhost',6345)
    conn = Client(address)
    conn.send(message)
    reply = conn.recv()
    conn.close()
    return reply
def triggerEvent( type, scheduleMethod, *args ):
    """
    This function inserts an event into CHOTestMonkey
    """
    host = "localhost"
    port = 6000
    address = ( host, port )
    conn = Client( address )
    request = []
    request.append( 1 )
    request.append( type )
    request.append( scheduleMethod )
    for arg in args:
        request.append( arg )
    conn.send( request )
    response = conn.recv()
    while response == 11:
        conn.close()
        time.sleep( 1 )
        conn = Client( address )
        conn.send( request )
        response = conn.recv()
    if response == 10:
        print "Event inserted:", type, scheduleMethod, args
    elif response == 20:
        print "Unknown message to server"
    elif response == 21:
        print "Unknown event type to server"
    elif response == 22:
        print "Unknown schedule method to server"
    elif response == 23:
        print "Not enough argument"
    else:
        print "Unknown response from server:", response
    conn.close()
class LockOutputFrequency(ExternalParameterBase):

    className = "Digital Lock Output Frequency"
    _outputChannels = {"OutputFrequency": "MHz", "Harmonic": ""}

    def __init__(self, name, config, globalDict, instrument="localhost:16888"):
        logger = logging.getLogger(__name__)
        ExternalParameterBase.__init__(self, name, config, globalDict)
        logger.info( "trying to open '{0}'".format(instrument) )
        host, port = instrument.split(':')
        self.instrument = Client((host, int(port)), authkey=b"yb171")
        logger.info( "opened {0}".format(instrument) )
        self.setDefaults()
        self.initializeChannelsToExternals()
        
    def setValue(self, channel, v):
        self.instrument.send( ('set{0}'.format(channel), (v, ) ) )
        result = self.instrument.recv()
        if isinstance(result, Exception):
            raise result
        return result
        
    def getValue(self, channel):
        self.instrument.send( ('get{0}'.format(channel), tuple() ) )
        result = self.instrument.recv()
        if isinstance(result, Exception):
            raise result
        return result
        
    def close(self):
        del self.instrument
Пример #11
0
class ThreadedExponentClient(ExponentClient):
    def __init__(self, ip, port, password):
        super(ThreadedExponentClient, self).__init__(ip, port, password)

        self.conn = Client((self.ip, self.port))

    def _auth(self, password):
        self.conn.send(password)
        auth_value = self.conn.recv()

        if auth_value == 'AUTH':
            print("Authorized")
            return True
        else:
            raise RuntimeError("Invalid Password")
            return False

    def __del__(self):
        print("Entering del")
        if self.__dict__.get('conn') != None:
            self.conn.close()

    def send(self, value):
        self.conn.send(value)
        return self.conn.recv()
def main():
    connection = Client(('localhost', 6060))
    with open(r'PATH/TO/list.txt', 'rb') as samples:
        for sample in samples:
            print("Sending sample " + sample.rstrip())
            connection.send(sample.rstrip())
            print connection.recv()
Пример #13
0
def send_msg(msg):
    #print("starting send: open...")
    conn = Client(address)
    #print("starting send: send...")
    conn.send(msg)
    #print("starting send: close...")
    conn.close()
Пример #14
0
class RpcClient:
    def __init__(self, host: str = "localhost", port: int = 17000, authkey: bytes = b"keykey"):
        self._connection = None

        self.host = host
        self.port = port
        self.authkey = authkey

    def connect(self):
        try:
            self._connection = Client(address=(self.host, self.port), authkey=self.authkey)
            rep = self.connect_test()
            print(rep)
        except:
            if self._connection:
                self.close()
            traceback.print_exc()

    def close(self):
        self._connection.close()
        print("连接关闭")

    def __getattr__(self, name):
        def do_rpc(*args, **kwargs):
            self._connection.send(json.dumps((name, args, kwargs)))
            rep = json.loads(self._connection.recv())

            if rep[0]:
                return rep[1]
            else:
                self.close()
                raise RemoteException(rep[1])

        return do_rpc
Пример #15
0
def serverrun_single(problem_id, code, input_data, output_data):
    import acwingcli.config as config
    url = config.problem_cache[eval(problem_id)]['link']
    address = ('localhost', 6001)
    conn = Client(address, authkey=b'1234')
    local_server_message = {
        'activity': 'run',
        'url': url,
        'code': code,
        'input_data': input_data
    }
    conn.send(json.dumps(local_server_message))
    while True:
        early_exit = False
        if conn.poll(20) == True:
            response = json.loads(conn.recv())
            if 'local_debug_message' in response.keys():
                display_debug_message(response)
            elif 'status' in response.keys():
                early_exit = display_run_status(response, problem_id,
                                                input_data, output_data)
        else:
            sys.stdout.write(Fore.GREEN + Style.BRIGHT + 'TIME OUT' +
                             Style.RESET_ALL)
            sys.stdout.flush()
        if early_exit == True:
            break
    conn.close()
Пример #16
0
def offline(conn, id, cuentas, rel_lastacp_dirl, contactos, m):
    if m[0][0] in cuentas.keys():
        if cuentas.get(m[0][0])[0] == m[0][1]:
            if cuentas.get(m[0][0])[1] == 'Online':
                if cuentas.get(m[0][0])[2] == id:
                    cuentas[m[0][0]] = m[0][1], 'Offline'
                    rel_lastacp_dirl.pop(id)
                    answer = ["notify_quit", True]
                    conn.send(answer)
                    for client, info in cuentas.items():
                        if info[1] == 'Online':
                            if not info[2] == id:
                                if client in contactos.get(m[0][0]):
                                    conn = Client(address=info[3][0],
                                                  authkey=info[3][1])
                                    conn.send(
                                        ["server_notify_quit_user", m[0][0]])
                                    conn.close()
                else:
                    answer = ['notify_quit', False]
                    conn.send(answer)
            else:
                answer = ["notify_quit", False]
                conn.send(answer)
        else:
            answer = ["notify_quit", False]
            conn.send(answer)
    else:
        answer = ["notify_quit", False]
        conn.send(answer)
Пример #17
0
class UIListener:
    def __init__(self, address, port, authkey):
        self.client = Client((address, port), authkey=authkey)

    def get_args(self, n):
        return [self.client.recv() if self.client.poll(0.5) else None for _ in range(n)]

    def listenloop(self):
        keepalive = True

        try:
            while keepalive:
                while self.client.poll():
                    data = self.client.recv()
                    print('{}: {}'.format('x64' if utils.is64bit() else 'x86', data))

                    if data == 'close':
                        keepalive = False
                    else:
                        func = _interface[data]
                        self.client.send(func(*self.get_args(func.__code__.co_argcount)))
                        print('{}: sent response to {}'.format('x64' if utils.is64bit() else 'x86', data))

                time.sleep(0.05)
        except EOFError or ConnectionError:
            pass

            self.client.close()
Пример #18
0
class IPCClient:

    def __init__(self):
        self.subscribers = defaultdict(set)
        self.conn = None
        self.thread = None

    @property
    def running(self):
        if self.thread:
            return self.thread.is_alive()
        return False

    def run(self):
        return

    def start_in_seperate_process(self, pipe):
        self.conn = Client(ipc_server.address, authkey=ipc_server.authkey)
        try:
            self.run()
        except Exception:
            self.conn.close()
            #Cause traceback objects aren't pickle'able, whytho.jpg
            pipe.send("".join(traceback.format_exception(*sys.exc_info())))

    def attach(self, event, func):
        self.subscribers[event].add(func)

    def start(self):
        recv_pipe, send_pipe = Pipe()
        self.thread = Process(target=self.start_in_seperate_process, daemon=True, args=(send_pipe,))
        self.thread.start()

        try:
            if recv_pipe.poll(0.5):
                exc_info = recv_pipe.recv()
                logging.error(f'Error starting process, got exception:\n{exc_info}')
                self.thread.join()
                raise Exception(exc_info.splitlines()[-1])
        finally:
            recv_pipe.close()
            send_pipe.close()

    def dispatch_event(self, event, msg):
        self.conn.send((event, msg))
        try:
            topic, data = self.conn.recv()
            if topic == Events.EXCEPTION:
                logging.debug(f"Received data back from event: {event} - ERROR - {data}")
                raise Exception(data)

            logging.debug(f"Received data back from event: {event} - OK")
            return data
        except EOFError:
            pass

    def stop(self):
        self.thread.kill()
        self.thread.join()
        logging.debug(f"Stopping process pid: {self.thread.pid}, name:{self.thread.name}/{self.thread.ident}")
Пример #19
0
def parse_to_modelManagement(task, frame, nickname):
    global local_address_m
    conn = Client(local_address_m, authkey = 'localModel')
    conn.send([task, frame, nickname])
    results = conn.recv()
    conn.close()
    return results
Пример #20
0
 def send_ipc_message(self, message="Empty Data..."):
     try:
         conn = Client((self.ipc_address, self.ipc_port), authkey=self.ipc_authkey)
         conn.send(message)
         conn.send('close connection')
     except Exception as e:
         print(repr(e))
Пример #21
0
 def send(self, packet):
     address = ('localhost', self.port)
     conn = Client(address, authkey=self.pwd)
     self._printDebug("MultiBus,Client: send")
     conn.send(packet)
     conn.send('close')
     conn.close()
Пример #22
0
def shutdown_server():
    try:
        address = ('localhost', 6001)
        conn = Client(address, authkey=b'1234')
        local_server_message = {'activity': 'stopserver'}
        conn.send(json.dumps(local_server_message))
        while True:
            early_exit = False
            if conn.poll(20) == True:
                cmdwrite.client_debug(
                    'shutdown message sent, waiting for response')
                response = json.loads(conn.recv())
                if 'local_debug_message' in response.keys():
                    display_debug_message(response)
                    if (response['local_debug_message'] == 'close'):
                        early_exit = True
                        cmdwrite.client_debug(
                            'server shutdown confirmation received')
                if early_exit == True:
                    break
            else:
                cmdwrite.client_debug(
                    'no server shutdown confirmation received, exit')
                break
    except ConnectionRefusedError:
        cmdwrite.client_debug('no server connection, exit')
    except EOFError:
        cmdwrite.client_debug('no server connection, exit')
Пример #23
0
class RsClient:

	def __enter__(self):
		"""no init"""

	def __exit__(self, type=None, value=None, tb=None):

		#self.conn may not exist so expect that it may fail.
		try:
			self.conn.close()
		except:
			pass

	def start(self, host='localhost', port=8000, key='8457#$%^&3648'):

		address = (host, port)
		self.conn = Client(address)

	def send(self, data):
		try:
			self.conn.send(data)
		except:
			self.stop()

	def stop(self):
		self.conn.close()
Пример #24
0
def notify_quit_client(id,clients,addressbook): 
    for client, client_info in clients.items():
            if client in addressbook[id]:
                print "sending quit client to", client
                conn = Client(address=client_info[0], authkey=client_info[1])
                conn.send(("server_notify_quit_user", id))
                conn.close()
Пример #25
0
class RemoteRequestor(object):
    def __init__(self, host, port, authkey):
        address = (host, port)
        self.conn = None
        self.retries = 0
        while self.conn is None and self.retries < 8:
            try:
                self.conn = Client(address)
            except ConnectionRefusedError as e:
                self.retries = self.retries + 1

    def execute(self, cmd):
        caller = getframeinfo(stack()[2][0])
        lineno = caller.lineno
        cmd.insert(0, lineno)
        try:
            self.conn.send(cmd)
            reply = self.conn.recv()
        except BaseException as e:
            reply = None
        return reply

    def close(self):
        try:
            self.conn.close()
        except BaseException as e:
            pass
Пример #26
0
def notify_new_client(id,clients,addressbook): 
    for client, client_info in clients.items():
        if not client == id and client in addressbook[id]:
            print "sending new client to", client
            conn = Client(address=client_info[0], authkey=client_info[1])
            conn.send(("server_notify_go_online_user", id))
            conn.close()
Пример #27
0
 def send(self, msg):
     # TODO: Busy wait will do for initial startup but for dealing with server down in the middle of things
     # TODO: then busy wait is probably inappropriate.
     if self.port == 5555:
         self.redis.rpush('flowqueue', msg)
     else:
         while True: # keep going until we break out inside the loop
             try:
                 self.logger.debug('Attempting to connect to '+self.serverName+' server at '+str(self.address)+' port '+str(self.port))
                 conn = Client((self.address, self.port))
                 self.logger.debug('Connect to '+self.serverName+' successful.')
                 break
             except SocketError as serr:
                 if serr.errno == errno.ECONNREFUSED:
                     self.logger.debug('Connect to '+self.serverName+' failed because connection was refused (the server is down). Trying again.')
                 else:
                     # Not a recognized error. Treat as fatal.
                     self.logger.debug('Connect to '+self.serverName+' gave socket error '+str(serr.errno))
                     raise serr
             except:
                 self.logger.exception('Connect to '+self.serverName+' threw unknown exception')
                 raise
         self.logger.debug('PCTRLSEND ' + str(msg))
         conn.send(msg)
         self.logger.debug('TRYCONNCLOSE trying to close the connection in pctrl')
         conn.close()
Пример #28
0
def parse_frame_list(video_id, begin, end, fps):
    global local_address_d
    conn = Client(local_address_d, authkey="localData")
    conn.send([video_id, begin, end, fps])
    framelist = conn.recv()
    conn.close()
    return framelist
Пример #29
0
class ExabgpHook():
    def __init__(self, sock_path):
        self.conn = None
        self.sock_path = os.environ.get('FBGP_EXABGP_SOCK',
                                        '/var/log/fbgp/exabgp_hook.sock')
        self.running = False

    def run_forever(self):
        self.conn = Client(self.sock_path, 'AF_UNIX')
        self.running = True
        eventlet.spawn(self.recv_from_fbgp_loop)
        self.recv_from_exabgp_loop()

    def recv_from_exabgp_loop(self):
        while self.running:
            line = stdin.readline().strip()
            self.conn.send(line)
            # have no idea why the below line is important,
            # without it no data is received from conn
            time.sleep(0)

    def recv_from_fbgp_loop(self):
        while self.running:
            try:
                data = self.conn.recv()
                stdout.write(data + '\n')
                stdout.flush()
            except:
                self.conn.close()
                break
Пример #30
0
class Bigram():
    def __getitem__(self, word):
        global _phrases

        # If a phrases model is already loaded, just use that
        if _phrases is not None:
            self.conn = None

        # Otherwise, try to connect to the separate process.
        # Fall back to loading the phrase model here
        elif not hasattr(self, 'conn'):
            try:
                print('Connecting to phrases process...')
                address = ('localhost', 6001)
                self.conn = Client(address, authkey=b'password')
                print('Done connecting to phrases')

            except ConnectionRefusedError:
                self.conn = None
                print('Could not connect to phrases process,')
                print('Loading phrases model...')
                _phrases = Phrases.load('data/bigram_model.phrases')
                print('Done loading phrases')

        if self.conn is not None:
            self.conn.send(word)
            return self.conn.recv()
        else:
            return _phrases[word]
Пример #31
0
def triggerEvent(type, scheduleMethod, *args):
    """
    This function inserts an event into CHOTestMonkey
    """
    host = "localhost"
    port = 6000
    address = (host, port)
    conn = Client(address)
    request = []
    request.append(2)
    request.append(type)
    request.append(scheduleMethod)
    for arg in args:
        request.append(arg)
    conn.send(request)
    response = conn.recv()
    while response == 11:
        time.sleep(1)
        conn.send(request)
        response = conn.recv()
    if response == 10:
        print "Event inserted:", type, scheduleMethod, args
    elif response == 20:
        print "Unknown message to server"
    elif response == 21:
        print "Unknown event type to server"
    elif response == 22:
        print "Unknown schedule method to server"
    elif response == 23:
        print "Not enough argument"
    else:
        print "Unknown response from server:", response
    conn.close()
Пример #32
0
class Server:
    def __init__(self):
        self.connection = None

    def connect(self):
        """
        Establishes a connection to the worker.
        """
        while not self.connection:
            try:
                self.connection = Client(Config.address)
            except ConnectionRefusedError:
                print("Connection refused. Retrying in 1 second...")
            sleep(1)
        print("Connection established!")

    def task(self, job: Job):
        """
        Send a job to the worker.
        """
        self.connection.send(job)

    def query(self, query: Query):
        """
        Query the worker for a value.
        """
        self.connection.send(query)
        try:
            return self.connection.recv()
        except BlockingIOError:
            print("Query not available")
            return None
Пример #33
0
def connect_node(node):
    try:

        #connect
        address = (node[0], int(node[1]))
        connect = Client(address, authkey="hi")
        connect.send('Hello from supervisor process')

        #check connection
        try:
            deliver_challenge(connect, authkey="hi")
            print "Node {} connected".format(node)
            node[2] = True
            return connect

        except EOFError:
            traceback.print_exc()
            print "Could not connect to node {} {}".format(node[0], node[1])
            node[2] = False
            con.close()

    except:
        traceback.print_exc()
        print "Could not connect to node {} {}".format(node[0], node[1])
        node[2] = False
Пример #34
0
    def send(self, msg):
        # TODO: Busy wait will do for initial startup but for dealing with server down in the middle of things
        # TODO: then busy wait is probably inappropriate.
        while True:  # keep going until we break out inside the loop
            try:
                self.logger.debug('Attempting to connect to ' +
                                  self.serverName + ' server at ' +
                                  str(self.address) + ' port ' +
                                  str(self.port))
                conn = Client((self.address, self.port))
                self.logger.debug('Connect to ' + self.serverName +
                                  ' successful.')
                break
            except SocketError as serr:
                if serr.errno == errno.ECONNREFUSED:
                    self.logger.debug(
                        'Connect to ' + self.serverName +
                        ' failed because connection was refused (the server is down). Trying again.'
                    )
                else:
                    # Not a recognized error. Treat as fatal.
                    self.logger.debug('Connect to ' + self.serverName +
                                      ' gave socket error ' + str(serr.errno))
                    raise serr
            except:
                self.logger.exception('Connect to ' + self.serverName +
                                      ' threw unknown exception')
                raise

        conn.send(msg)

        conn.close()
Пример #35
0
class Runner:
    data_: Any
    models_: List[Model]
    address_: Tuple[str, int]
    client_: Optional[Connection]

    def __init__(self, data, models, address):
        self.data_ = data
        self.models_ = models
        self.address_ = address
        self.client_ = None

    def __enter__(self):
        self.client_ = Client(self.address_)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.client_.close()

    def __call__(self):
        while True:
            data = self.client_.recv()
            if data is None:
                break
            model, parameters = data
            result = self.models_[model].create(parameters)(self.data_)
            self.client_.send((
                model,
                parameters,
                result,
            ))
Пример #36
0
def main():

    rec_data()

    res = compute()

    if role == '0':
        res_list = [int(res)]
        cpter0 = Listener(addr2)
        print("------节点0等待其他节点的结果-------")
        for i in range(int(total_node)-1):
            c0 = cpter0.accept()
            t = c0.recv()
            t = int(t)
            res_list.append(t)
        # print(res_list)
        #发送给控制节点
        cpter = Client(addr)
        print("------结果规约成功,发送至控制节点-----")
        cpter.send(max(res_list))

    else:
        cpter_other = Client(addr2)
        cpter_other.send(res)
        print("--------计算结束,发送给0-------")
Пример #37
0
def shutdown_metric(metric_server_addresses, authkey):
    """ This function tells all of the SimulationPotential instances running on the addresses in metric_server_addresses to shutdown. This is called when a SimulationClient instance shuts down.

    Args:
      metric_server_addresses: A list of tuples of the form (str, int) containing the hostnames and port numbers of the SimulationPotential instances.
      authkey (str): The password used in order to communicate with the SimulationPotential instances.

    Returns:
      float: The length of the curve with metric values in metric.

    """

    # For each SimulationPotential instance...
    for address in xrange(len(metric_server_addresses)):

        # Try making contact with the SimulationPotential instance...
        try:
            # Establish a connection with the SimulationPotential
            metric_server = Client(metric_server_addresses[address], authkey=authkey)

            # Send a status code indicating the SimulationPotential instance should stop running.
            metric_server.send({'status_code': comm_code('KILL')})

            # Close the connection.
            metric_server.close()

        # If contact with the SimulationPotential instance cannot be made then...
        except socket.error:
            # Make a note in the log which SimulationPotential couldn't be contacted.
            logging.warning('Failed to Make Connection to SimulationPotential at '
                          + str(metric_server_addresses[address]) + '.')
Пример #38
0
    def run(self):
        while True:
            connection = self.listener.accept()
            message = []
            try:
                message = connection.recv()
            except:
                pass
            if len(message) == 3:
                self.lock.acquire()
                if message[0] in self.users:
                    client_address = ('localhost', message[1])
                    response = Client(client_address,
                                      authkey=b'secret password')

                    public_key = KeySaver.load_public_key(message[2])
                    encrypted_key = Encryptor.encrypt_symmetric_key(
                        public_key, self.key)

                    response.send(encrypted_key)
                    response.close()
                else:
                    print('Unauthorised access by %s' % (message[0]))
                self.lock.release()

            connection.close()
Пример #39
0
 def POST(self):
     c = Client(('localhost', 5000))
     data = web.input(test="default")
     print data.priority + data.source + data.destination
     c.send((data.priority, data.source, data.destination))
     print('Got:', c.recv())
     return "success"
Пример #40
0
        def call(*args, **kwargs):
            global _recursive_conn_lock
            if _recursive_conn_lock:
                raise AssertionError, 'BUG: Recursive client connection'
                # Avoid hanging because we call the socket while the
                # server is blocking for our return value on the pipe.
                # If this is an issue blocking functionality,
                # re-route the call to the open pipe for which the
                # server is waiting.

            #~ if self._client_proxy_authkey is None:
                #~ self._client_proxy_authkey = AUTHKEY_FILE.raw()

            msg = RemoteMethodCall(self._obj, name, args, kwargs)
            logger.debug('Remote call from %i: %s', os.getpid(), msg)
            #~ print "CLIENT >>%s<<" % self._client_proxy_authkey
            #~ conn = Client(SERVER_ADDRESS, authkey=self._client_proxy_authkey)
            conn = Client(SERVER_ADDRESS, SERVER_ADDRESS_FAMILY)
            conn.send(msg)
            if not msg.async:
                re = conn.recv()
                logger.debug('Remote call returned to %i: %s', os.getpid(), re)
                if isinstance(re, Exception):
                    raise re
                else:
                    return re
Пример #41
0
def get_json():
    # Get the current values
    c = Client(("localhost", 25000))
    c.send("get")
    now = c.recv()

    # Now we parse all the data out of the results!
    data = {}
    data["IN_Temp"] = now.In_Temp
    data["IN_Humid"] = now.In_Humid
    data["OUT_Temp"] = now.Out_Temp
    data["OUT_Humid"] = now.Out_Humid
    data["Out_Wind_Now"] = now.Out_Wind_Now
    data["OUT_Wind_Avg"] = now.Out_Wind_Avg
    data["OUT_Wind_Max"] = now.Out_Wind_Max
    data["OUT_Rain_Today"] = now.Out_Rain_Today
    data["OUT_Rain_Last_24h"] = now.Out_Rain_Last_24h
    data["OUT_Rain_Since_Reset"] = now.Out_Rain_Since_Reset
    data["ATTIC_Temp"] = now.Attic_Temp
    data["ATTIC_Humid"] = now.Attic_Humid
    data["NOW_URL"] = now.Now_URL
    data["NOW_Feel"] = now.Now_Feel
    data["NOW_Feel_High"] = now.Now_Feel_High
    data["NOW_Feel_Low"] = now.NOW_Feel_Low
    data["SYSTEM_CPU"] = now.System_CPU
    data["SYSTEM_RAM"] = now.System_RAM

    # Now return the json as a string
    return json.dumps(data)
Пример #42
0
    def send(self, msg):
        #conn = Client((self.address, self.port), authkey=str(self.key))
        conn = Client((self.address, self.port))

        conn.send(json.dumps(msg))

        conn.close()
Пример #43
0
def run_client(host, port):
    capture = OpenCVCapture()
    visualizer = Open3d_visualizer()
    client = Client((host, port))
    data_cacher = np.zeros((6890,3))

    while True:
        frame = capture.read()
        if frame is not None:
            data = frame
        else:
            data = ['waiting for the cam']
        data_string = pickle.dumps(data)
        client.send(data_string)

        if frame is not None:
            data_bytes = client.recv()
            data_recieve = pickle.loads(data_bytes)
            if not isinstance(data_recieve, list):
                break_flag = visualizer.run(data_recieve, frame[:,:,::-1])
                data_cacher = data_recieve
            else:
                break_flag = visualizer.run(data_cacher, frame[:,:,::-1])
            if break_flag:
                break
def generate(port, msg, f_writer):
    os.system(terminal_start_command + " " + slave_file_name + " " + str(port))
    while (True):
        try:
            address = ('localhost', port)
            conn = Client(address, authkey=b'secret password')
            conn.send(msg)  #send variants to *flappy_bird_variant_generate.py*
            print(" param update:", msg)
            msg = conn.recv(
            )  #wait for response from *flappy_bird_variant_generate.py*
            if (msg == None):
                print("Failed")  # variants sent are not playable for ai agent
            elif (len(msg) == 2):
                print("Failed", msg)  # print score
                f_writer.writerow(["Failed", msg[1], msg[0], ""])
            else:
                print(msg)  # variants sent are playable for ai agent
                f_writer.writerow(msg)
            conn.close()
            break
        except ConnectionRefusedError:  # usually *flappy_bird_variant_generate.py* is not started yet, so waits till it is running
            print("refused")
            sleep(3)
        except EOFError:  # usually *flappy_bird_variant_generate.py* training is complete
            print("flappy_bird_variant_generate.py server closed")
            break
        except Exception as e:
            print("Error occurred " + str(e))
            break
Пример #45
0
	def send(self, msg):

		try:
			connection = Client(self.address, authkey=self.auth)
			connection.send(msg)
			connection.close()
		except ConnectionRefusedError:
			print('Connection Refused')
Пример #46
0
 def send(self, command, payload = None):
     address = ('localhost', self.port)
     #print address
     conn = Client(address)
     conn.send((command, payload))
     response, response_payload = conn.recv()
     conn.close()
     return response_payload
Пример #47
0
def reset_rain():
    # Reset rain_since_reset in the table
    # (╯°□°)╯︵ ┻━┻
    c = Client( ('localhost', 25000) )
    c.send("reset_rain")
    result = c.recv()
    
    return "reset!"
Пример #48
0
 def _send(self, msg):
     conn = Client(self.address, authkey=self.authkey)
     conn.send(msg)
     result = conn.recv()
     conn.close()
     if result:
         self._locked = True
     return result
Пример #49
0
class RPCProxy(RPCObject):
    """
    RPCProxy, object running in child processes that connects to an :class:`RPCServer`
    object.
    """
    def __init__(self, address, authkey):
        super(RPCProxy, self).__init__()
        self._functions = { }
        self._quitnotifiers = set()
        self._conn = Client(address, authkey=authkey)
        self._conn.send(json.dumps({"name" : _mp.current_process().name, "pid" : os.getpid()}))
        self._should_exit = False
        self.register_function(self.exit_now, "exit")
        def _exit(*args):
            self.exit_now()
        signal.signal(signal.SIGINT, _exit)
        signal.signal(signal.SIGTERM, _exit)

    def listen(self):
        def handle_client(client_c):
            while not self._should_exit:
                try:
                    func_name, args, kwargs = client_c.recv()
                except EOFError:
                    self.exit_now()
                    break
                try:
                    r = self._functions[func_name](*args,**kwargs)
                    client_c.send(r)
                except Exception as e:
                    client_c.send(e)
        self.t = Thread(target=handle_client, args=(self._conn,))
        self.t.daemon = True
        self.t.start()

    def register_exit_notification(self, func):
        self._quitnotifiers.add(func)

    def remove_exit_notification(self, func):
        try:
            self._quitnotifiers.remove(func)
        except KeyError: pass

    def exit_now(self):
        log("Exit requested")
        self._should_exit = True
        for f in self._quitnotifiers:
            f()
        return True

    def should_exit(self):
        return self._should_exit

    def register_function(self, func, name = None):
        if name is None:
            name = func.__name__
        self._functions[name] = func
Пример #50
0
 def send_update(self, id, route):
     # TODO: Explore what is better, persistent client sockets or
     # new socket for each BGP update
     "Send this BGP route to participant id's controller"
     logger.debug("Sending a route update to participant "+str(id))
     conn = Client(tuple(self.participants[id].eh_socket), authkey = None)
     conn.send(json.dumps({'bgp': route}))
     conn.recv()
     conn.close()
Пример #51
0
 def method(*args, **kwargs):
     connection = Client(address, authkey=authkey)
     connection.send([method_name, args, kwargs])
     result = connection.recv()
     connection.close()
     if result['type'] == 'result':
         return result['data']
     else:
         raise Exception(result['data'])
Пример #52
0
 def _query(self, message):
     connection = Client(self.address, family='AF_INET')
     connection.send(message)
     response = connection.recv()
     connection.close()
     if response['type'] == 'result':
         return response['data']
     else:
         raise DatabaseException(response['data'])
Пример #53
0
    def TryToConnect(self,child,host,port,n):
        address = (host,port)
#        address = ('jeremyfisher.math.udel.edu', 6000)
        #address = ('nutkin', 6000)
        conn = Client(address, authkey='secret password')
        conn.send(pickle.dumps(n,pickle.HIGHEST_PROTOCOL))
        vdata = pickle.loads(conn.recv())
        conn.send('close')
        conn.close()
        child.send(vdata)
Пример #54
0
def rebuild_handle(pickled_data):
    address, handle, inherited = pickled_data
    if inherited:
        return handle
    sub_debug('rebuilding handle %d', handle)
    conn = Client(address, authkey=current_process().authkey)
    conn.send((handle, os.getpid()))
    new_handle = recv_handle(conn)
    conn.close()
    return new_handle
Пример #55
0
def update_blackboard(nearby_devices):
    conn = Client(address)
    user = "******"
    for device in nearby_devices:
        if device in user1_devices:
            user = "******"
            break
    conn.send('PUT:user,' + str(user))
    conn.send('close')
    conn.close()
Пример #56
0
 def send(self, *args):
     """
     Send a command to the listener. Add the .calc_id as last argument.
     """
     if self.address:
         client = Client(self.address, authkey=self.authkey)
         try:
             client.send(args + (self.calc_id,))
         finally:
             client.close()
Пример #57
0
def run_backend(replace=False, exit=False, w2v_vector_file=W2V_VECTOR_FILE, temp_startup_server=False):
  repr_req_count = 0

  send_exit_command_after_init = False

  if not temp_startup_server:
    try:
      print('Connecting to backend.')
      conn = Client(BACKEND_ADDRESS, family=BACKEND_CONNECTION_FAMILY, authkey=BACKEND_PASSWORD)
      if not replace and not exit:
        conn.send({'command': 'CAPABILITIES'})
        msg = conn.recv()
        if msg['status'] == 'OK' and (msg['value'] == 'FULL' or msg['value'] == 'W2V_ONLY'):
          print('There is already an existing daemon with all neccessary capacities. Exiting.')
          sys.exit()
        else:
          print msg
          print('Found a running backend without required capabilities. Telling it to exit after init.')
          send_exit_command_after_init = True
      else: 
        print('Found a running backend. Telling it to exit after init.')
        send_exit_command_after_init = True
    except Exception, e:
      print(str(e))
      print(str(traceback.format_exc()))
      print('Did not manage to find a backend to kill.')

    if exit:
      print('Exiting.')
      sys.exit()

    if not send_exit_command_after_init:
      # The temp_startup_serer will take care of requests until startup (init()) is complete.
      p = Process(target=run_backend, kwargs={'temp_startup_server': True})
      p.start()
    
    init(w2v_vector_file=w2v_vector_file)
    
    # either temp_startup_server backend, or a previously running backend.
    print('Connecting to temp_startup_server (or previously running) backend.')
    conn = Client(BACKEND_ADDRESS, family=BACKEND_CONNECTION_FAMILY, authkey=BACKEND_PASSWORD)
    conn.send({'command': 'EXIT_NOW'})
    conn.close()
    conn = None
    if not send_exit_command_after_init:
      print('Waiting 1 sec for temp_startup_server backend to clean up.')
      time.sleep(1)
    else:
      print('Waiting 30 sec for previously running backend to clean up.')
      time.sleep(30)
      
    if not send_exit_command_after_init:
      p.terminate()
      print('temp_startup_server backend is now terminated.')
Пример #58
0
 def method(self, *args):
     args = list(args)
     args.insert(0, attribute)
     connection = Client(self.address, authkey=self.authkey)
     connection.send(dumps(args))
     result = loads(connection.recv())
     connection.close()
     if result[0] == 'RESULT':
         return result[1]
     else:
         raise MemoClientException(result[1])
Пример #59
0
class CliClient(cmd.Cmd):

    def __init__(self,address,id):
        self.id = id
        self.connection = Client(address, authkey='secret password')
        cmd.Cmd.__init__(self)

    def onecmd(self,line):
        self.connection.send(("creator",line))
        while self.connection.poll(0.1):
            print self.connection.recv()