def chainsync(self): redis_client = redis.Redis(host='localhost', port=6379, db=0) ip_list = [] nodes_map = utils.decode_redis(redis_client.hgetall("nodes_map")) for ip_addr, raw_data in nodes_map.items(): if ip_addr in settings.EXPLORER_IP: continue ip_list.append(ip_addr) # IP chosing method is under development! ip = random.choice(ip_list) udp = UDPHandler() context = zmq.Context() socket = context.socket(zmq.REP) udp.getchainlength({"ip_addr": ip}) socket.connect("tcp://127.0.0.1:%s" % settings.SYNC_ZMQ_PORT) res = json.loads(socket.recv_string()) length = res["body"] socket.send_string("Recieved Chain Length") socket.close() mylen = redis_client.llen("chain") if mylen == 0: for i in range(0, length): udp.getblockbyheight({"height": i, "ip_addr": ip}) socket.connect("tcp://127.0.0.1:%s" % settings.SYNC_ZMQ_PORT) res = json.loads(socket.recv_string()) socket.send_string("Recieved a block of the chain!!!") socket.close() blchain = Blockchain() blchain.add_block(res["body"]) # chain verification verf = Verification() msg = verf.full_chain_verify() if msg != "verified": return self.chainsync() elif mylen > length: return self.chainsync() elif mylen == length: return elif mylen < length: for i in range(mylen, length): udp.getblockbyheight({"height": i, "ip_addr": ip}) socket.connect("tcp://127.0.0.1:%s" % settings.SYNC_ZMQ_PORT) res = json.loads(socket.recv_string()) socket.send_string("Recieved a block of the chain!!!") socket.close() blchain = BlockChain() blchain.add_block(res["body"]) # chain verification verf = Verification() msg = verf.full_chain_verify() if msg != "verified": return self.chainsync()
def recv_gym(socket, flags=0, copy=True, track=False): md = socket.recv_json(flags=flags) msg = socket.recv(flags=flags, copy=copy, track=track) rew = float(socket.recv_string(flags=flags)) done = socket.recv_string(flags=flags) done = (done == "True") buf = buffer(msg) A = np.frombuffer(buf, dtype=md['dtype']) return (A.reshape(md['shape']), rew, done)
def connectZMQ(self): context = zmq.Context() socket = context.socket(zmq.SUB) print("[Network Control] Network Control connected to Decision Entity") socket.connect("tcp://132.187.12.97:6666") listenTo="6" if isinstance(listenTo, bytes): listenTo = listenTo.decode('ascii') socket.setsockopt_string(zmq.SUBSCRIBE, listenTo) #SPM performs prioritization of certain flows if mechanism=="spm": while True: string_received = socket.recv_string() listenTo, clientInfo, prio = string_received.split() prio=int(prio) client_info_splitted=clientInfo.split(":") client_ip=client_info_splitted[0] client_port=client_info_splitted[1] #Control whether it should be downloaded via priority queue or best-effort queue (default!) if prio==1: self.socket_trash.send("CMD addfilter GW1 "+str(client_ip)+" "+str(client_port)+" GW1_PRIORITY_1 1\n") else: print "deprio clients" self.socket_trash.send("CMD deletefilter GW1 "+str(client_ip)+" "+str(client_port)+" GW1_PRIORITY_1 1\n") #NADE performs bandwidth reservation for clients if mechanism=="nade": while True: string_received = socket.recv_string() listenTo, messageType,clientInfo, share, flow_id = string_received.split() print clientInfo client_info_splitted=clientInfo.split(":") client_ip=client_info_splitted[0] client_port=client_info_splitted[1] #if messagetype is register, then the flow needs to be added if messageType=="update": print ("UPDATE BANDWIDTH SHARE") comm = "CMD changebw "+str(flow_id)+" "+str(share)+"kbit 1\n" self.socket_trash.send("CMD changebw "+str(flow_id)+" "+str(float(share)*float(self.curr_bw))+"kbit 1\n") print clientInfo elif messageType == "register": print "REGISTER NEW INSTANCE" comm = "CMD addapp "+str(flow_id)+" "+str(client_ip)+" "+str(client_port)+" GW1\n" self.socket_trash.send("CMD addapp "+str(flow_id)+" "+str(client_ip)+" "+str(client_port)+" GW1\n") elif messageType == "delete": print "DELETE OLD INSTANCE" comm = "CMD delapp "+str(flow_id)+" "+str(client_ip)+" "+str(client_port)+" GW1\n" self.socket_trash.send(comm)
def listen_to_alive_messages(address, port): global context # context = zmq.Context() socket = context.socket(zmq.SUB) socket.bind("tcp://*:%s" % port) socket.setsockopt_string(zmq.SUBSCRIBE, '') print("Listening to ALIVE messages on %s:%s.." % (address, port)) db = mysql.connect(host="localhost", user="******", passwd="hydragang", database="data_nodes") cursor = db.cursor() while True: try: received_message = socket.recv_string(flags=zmq.NOBLOCK) node_id, message = received_message.split() node_id = int(node_id) # print("Tracker: received %s on %s:%s" % (received_message, address, port)) cursor.execute( "UPDATE node_table SET is_node_alive = TRUE WHERE node_number=%d" % node_id) cursor.execute( "UPDATE file_table SET is_node_alive = TRUE WHERE node_number=%d" % node_id) db.commit() # print(cursor.rowcount) except zmq.Again as e: cursor.execute( "UPDATE node_table SET is_node_alive = FALSE WHERE last_modified < NOW() - INTERVAL 1 MINUTE" ) cursor.execute( "UPDATE file_table SET is_node_alive = FALSE WHERE last_modified < NOW() - INTERVAL 1 MINUTE" ) db.commit()
def connectZMQ(self): context = zmq.Context() socket = context.socket(zmq.SUB) print("Tapas Player connection with zmq-Entity") socket.connect("tcp://192.168.1.2:4444") listenTo = "192.168.1.10:" + str(os.getpid()) print colored('im listening to ' + str(listenTo), 'green') #listenTo="192.168.1.2:"+str(getLocalport()) if isinstance(listenTo, bytes): listenTo = listenTo.decode('ascii') socket.setsockopt_string(zmq.SUBSCRIBE, listenTo) while True: try: string_received = socket.recv_string() listenTo, delegated_level = string_received.split() print colored("received prio status", 'red') print colored("[3] execute fetchNExtSegment() from here", 'blue') print colored("[!!!!!!] level delegate i received: " + str(delegated_level)) self.setDelegatedLevel(int((delegated_level))) self.fetchNextSegment() except KeyboardInterrupt: break
def download(DKip, DKport): try: context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://%s:%s" % (DKip, DKport)) print("after binding...") message = socket.recv_string() print("Received request: ", message) video = message vid = open(video, 'rb') vi = vid.read() dic = {'video': vi} socket.send_pyobj(dic) mess = {'Type': 'Downloaded', 'ip': DKip, 'port': DKport} # --------------JUST FOR TEST --------------# #----------------REMOVE THE COMMENT LATER----# context2 = zmq.Context() socket2 = context2.socket(zmq.REQ) socket2.connect("tcp://%s:%s" % (MasterIP, MasterPort)) socket2.send_pyobj(mess) except FileNotFoundError as e: print('file not found') except zmq.Again as e: pass
def connectZMQ(self): context = zmq.Context() socket = context.socket(zmq.SUB) print("Tapas Player connection with zmq-Entity") socket.connect("tcp://192.168.1.2:4444") curr_localPort=getLocalport() listenTo="192.168.1.10:"+str(curr_localPort) if isinstance(listenTo,bytes): listenTo = listenTo.decode('ascii') socket.setsockopt_string(zmq.SUBSCRIBE, listenTo) print('connLost is '+ str(self.connLost)) while self.connLost==False: try: print('connLost is '+ str(self.connLost)) string_received = socket.recv_string() print("=======================================") print('I RECEIVED A MESSAGE') print('IT IS MEANT TO BE FOR '+str(listenTo)) print('MY CURRENT LOCALPORT I HAVE TO LISTEN TO IS '+str(curr_localPort)) print("=======================================") listenTo, priostat = string_received.split() self.setPrio(int(float(priostat))) if not self.connLost: print colored("[_zmq got Answer()] I call fetchNextSegment() from if [1]",'red'); self.fetchNextSegment(curr_localPort) print colored("[_zmq got Answer ()] I called fetchNextSegment() from if [2]",'red'); if self.connLost: print colored('----------------------->>>>> Do not request because connection is lost','green') except KeyboardInterrupt: break
def _cmd_worker(self): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind(self.cmd_address) while True: cmd = socket.recv_string() res = self._handle_cmd(cmd) socket.send_string(res)
def replicate_test(file_path, replica_list): context = zmq.Context() print("Connecting to server (replica dataNodes)...") socket = context.socket(zmq.REQ) for replica_address in replica_list: print(replica_list) socket.connect("tcp://%s" % replica_address) f = open(file_path, 'rb') p = pickle.dumps(f.read()) z = zlib.compress(p) f.close() socket.send(z) ACK = socket.recv_string() print("ack after sending header", ACK) socket.send(z) ACK = socket.recv_string() print("ack after sending header", ACK) # socket.close() return replica_list
def server(): while True: time.sleep(3) try: context_rep = zmq.Context() socket = context_rep.socket(zmq.REP) socket.bind("tcp://*:8002") while True: message = socket.recv_string() print(message) except: pass
def recv_gym(socket, flags=0, copy=True, track=False): md = socket.recv_json(flags=flags) msg = socket.recv(flags=flags, copy=copy, track=track) rew = float(socket.recv_string(flags=flags)) done = socket.recv_string(flags=flags) done = (done == "True") misc = socket.recv_string(flags=flags) if "array" in misc: # this means somebody made a mistake and sent a numpy array instead of a list misc = misc.replace("array([", "[").replace("])}", "]}") try: misc = ast.literal_eval(misc) except BaseException as e: msg = "Exception while calling literal_eval() on '{}'':\n\n{}".format(misc, traceback.format_exc(e)) raise Exception(msg) buf = buffer(msg) A = np.frombuffer(buf, dtype=md['dtype']) return A.reshape(md['shape']), rew, done, misc
def on_recv(self, socket, ipc_pub): msg = socket.recv_string() if msg.startswith('notify'): try: payload = zmq_tools.serializer.loads( socket.recv(flags=zmq.NOBLOCK), encoding='utf-8') payload['subject'] except Exception as e: response = 'Notification mal-formatted or missing: {}'.format( e) else: ipc_pub.notify(payload) response = 'Notification recevied.' elif msg == 'SUB_PORT': response = self.g_pool.ipc_sub_url.split(':')[-1] elif msg == 'PUB_PORT': response = self.g_pool.ipc_pub_url.split(':')[-1] elif msg[0] == 'R': try: ipc_pub.notify({ 'subject': 'recording.should_start', 'session_name': msg[2:] }) response = 'OK' except IndexError: response = 'Recording command mal-formatted.' elif msg[0] == 'r': ipc_pub.notify({'subject': 'recording.should_stop'}) response = 'OK' elif msg == 'C': ipc_pub.notify({'subject': 'calibration.should_start'}) response = 'OK' elif msg == 'c': ipc_pub.notify({'subject': 'calibration.should_stop'}) response = 'OK' elif msg[0] == 'T': try: target = float(msg[2:]) except: response = "'{}' cannot be converted to float.".format(msg[2:]) else: raw_time = self.g_pool.get_now() self.g_pool.timebase.value = raw_time - target response = 'Timesync successful.' elif msg[0] == 't': response = repr(self.g_pool.get_timestamp()) elif msg[0] == 'v': response = '{}'.format(self.g_pool.version) else: response = 'Unknown command.' socket.send_string(response)
def notify(socket): """Sends notification to Pupil Remote""" notification = { "subject": "start_plugin", "name": "Annotation_Capture", "args": {} } topic = "notify." + notification["subject"] payload = serializer.dumps(notification, use_bin_type=True) socket.send_string(topic, flags=zmq.SNDMORE) socket.send(payload) return socket.recv_string()
def on_recv(self, socket, ipc_pub): msg = socket.recv_string() if msg.startswith('notify'): try: payload = zmq_tools.serializer.loads(socket.recv(flags=zmq.NOBLOCK), encoding='utf-8') payload['subject'] except Exception as e: response = 'Notification mal-formatted or missing: {}'.format(e) else: ipc_pub.notify(payload) response = 'Notification recevied.' elif msg == 'SUB_PORT': response = self.g_pool.ipc_sub_url.split(':')[-1] elif msg == 'PUB_PORT': response = self.g_pool.ipc_pub_url.split(':')[-1] elif msg[0] == 'R': try: ipc_pub.notify({'subject': 'recording.should_start', 'session_name': msg[2:]}) response = 'OK' except IndexError: response = 'Recording command mal-formatted.' elif msg[0] == 'r': ipc_pub.notify({'subject': 'recording.should_stop'}) response = 'OK' elif msg == 'C': ipc_pub.notify({'subject': 'calibration.should_start'}) response = 'OK' elif msg == 'c': ipc_pub.notify({'subject': 'calibration.should_stop'}) response = 'OK' elif msg == 'a': ipc_pub.notify({'subject':'accuracy_calibration'}) response = 'Set to accuracy calibration' elif msg == 's': ipc_pub.notify({'subject':'screen_marker_calibration'}) response = 'Set to screen marker calibration' elif msg[0] == 'T': try: target = float(msg[2:]) except: response = "'{}' cannot be converted to float.".format(msg[2:]) else: raw_time = self.g_pool.get_now() self.g_pool.timebase.value = raw_time-target response = 'Timesync successful.' elif msg[0] == 't': response = repr(self.g_pool.get_timestamp()) else: response = 'Unknown command.' socket.send_string(response)
def on_recv(self, socket, ipc_pub): msg = socket.recv_string() if msg.startswith("notify"): try: payload = zmq_tools.serializer.loads( socket.recv(flags=zmq.NOBLOCK), encoding="utf-8" ) payload["subject"] except Exception as e: response = "Notification mal-formatted or missing: {}".format(e) else: ipc_pub.notify(payload) response = "Notification recevied." elif msg == "SUB_PORT": response = self.g_pool.ipc_sub_url.split(":")[-1] elif msg == "PUB_PORT": response = self.g_pool.ipc_pub_url.split(":")[-1] elif msg[0] == "R": try: ipc_pub.notify( {"subject": "recording.should_start", "session_name": msg[2:]} ) response = "OK" except IndexError: response = "Recording command mal-formatted." elif msg[0] == "r": ipc_pub.notify({"subject": "recording.should_stop"}) response = "OK" elif msg == "C": ipc_pub.notify({"subject": "calibration.should_start"}) response = "OK" elif msg == "c": ipc_pub.notify({"subject": "calibration.should_stop"}) response = "OK" elif msg[0] == "T": try: target = float(msg[2:]) except: response = "'{}' cannot be converted to float.".format(msg[2:]) else: raw_time = self.g_pool.get_now() self.g_pool.timebase.value = raw_time - target response = "Timesync successful." elif msg[0] == "t": response = repr(self.g_pool.get_timestamp()) elif msg[0] == "v": response = "{}".format(self.g_pool.version) else: response = "Unknown command." socket.send_string(response)
def connect_pupil_capture(): """connect to pupil capture using zmq protocol""" try: context = zmq.Context() socket = zmq.Socket(context, zmq.REQ) socket.connect('tcp://' + ip + ':' + str(port)) socket.send_string("PUB_PORT") pub_port = socket.recv_string() pub_socket = zmq.Socket(context, zmq.PUB) pub_socket.connect('tcp://' + ip + ':{}'.format(pub_port)) return socket, pub_socket except Exception as err: print('Cannot connect to Pupil Capture', err) sys.exit()
def on_recv(self, socket, ipc_pub): msg = socket.recv_string() #if msg.startswith('notify'): if msg[0] == 'R': try: ipc_pub.notify({ 'subject': 'recording.should_start', 'session_name': msg[2:] }) response = 'OK' except IndexError: response = 'Recording command mal-formatted.' elif msg[0] == 'r': ipc_pub.notify({'subject': 'recording.should_stop'}) response = 'OK' elif msg == 'C': ipc_pub.notify({'subject': 'calibration.should_start'}) response = 'OK' elif msg == 'c': ipc_pub.notify({'subject': 'calibration.should_stop'}) response = 'OK' elif msg == 'V': ipc_pub.notify({'subject': 'accuracy_test.should_start'}) response = 'OK' elif msg == 'v': ipc_pub.notify({'subject': 'accuracy_test.should_stop'}) response = 'OK' else: t = self.g_pool.get_timestamp() t_frame = self.g_pool.capture._recent_frame.timestamp notification = { 'subject': 'trigger', 'label': msg, 'timestamp': t, 'recent_frame_timestamp': t_frame, 'duration': 0.0, 'record': True } ipc_pub.notify(notification) response = 'nbp_ok' socket.send_string(response)
def replicate(): context = zmq.Context( ) #connection with the master to get info(here is the server) socket_master_replicate = context.socket(zmq.REP) socket_master_replicate.bind("tcp://*:%s" % notify_replicate_port) while (True): parsed_json = json.loads(socket_master_replicate.recv_json()) replica_list = parsed_json["replicalist"] socket_master_replicate.send_string("ACK, replication info recieved") #here other nodes act as servers the one responsible for sending is the client #connection with data nodes print("Connecting to server (replica dataNodes)...") socket = context.socket(zmq.REQ) print(replica_list) #list_values = [ replica_address for replica_address in replica_list.values()] for replica_address in replica_list: print("replica address:", replica_address) socket.connect("tcp://%s" % replica_address) extension_index = len(parsed_json["filename"]) if "." in parsed_json["filename"]: extension_index = parsed_json["filename"].rfind(".") directory = "./" + parsed_json["username"] + "/" + str( parsed_json["filename"])[:extension_index] file_path = directory + "/" + parsed_json["filename"] f = open(file_path, 'rb') p = pickle.dumps(f.read()) z = zlib.compress(p) f.close() parsed_json["file"] = z for i in range(len(replica_list)): socket.send(pickle.dumps(parsed_json)) ACK = socket.recv_string() print("ack received after sending data to replicatio data nodes:", ACK)
def add_to_DB(port): global context socket = context.socket(zmq.SUB) socket.bind("tcp://*:%s" % port) socket.setsockopt_string(zmq.SUBSCRIBE, '') print("Listening to ADD_To_DB messages on port: %s.." % (port)) while True: # try: received_message = socket.recv_string(flags=zmq.NOBLOCK) data_node_id, client_id, file_name = socket.recv(2048).decode( 'utf-8').split('#') print("adding file from master tracker " + data_node_id) db = mysql.connect(host="localhost", user="******", passwd="hydragang", database="data_nodes") cursor = db.cursor() cursor.execute( "INSERT INTO file_table (user_id,node_number,file_name,file_path) VALUES (" + client_id + "," + data_node_id + ",'" + file_name + "','" + file_name + "');") db.commit() cursor.close() print("file added into DB!")
def server(): while True: time.sleep(3) try: context_rep = zmq.Context() socket = context_rep.socket(zmq.REP) socket.bind("tcp://*:8002") try: message = socket.recv_string() print(message) l = message.split(",") print(l) if l[0] == "p": respuesta = int(l[2]) - int(l[3]) print(respuesta) respuesta = str(respuesta) socket.send_string(respuesta) elif l[0] == "r": pass except: pass except: pass # print("ffffff")
def midas_recv(socket): address = socket.recv() socket.recv() # Empty sequence msg_type = socket.recv_string() message = socket.recv_string() return address, msg_type, message
def server(): while True: # time.sleep(2) try: context_rep = zmq.Context() socket = context_rep.socket(zmq.REP) socket.bind("tcp://*:" + mi_port) try: print("servidor ejecutando...") message = socket.recv_string() print(message) l = message.split("_") # print(l) # print(type(l[0])) #print("cualquier cosa") if l[0] == "p": if l[1] == yo: # aqui se devuelve enviando el puerto del sevicio hasta llegar a cliente print(l) ruta = l[5] # se extrae el diccionario_string ruta # se convierte a diccionario ruta_dic = json.loads(ruta) # agrego mi servicio/nodo a la ruta ruta_dic[yo] = {"ip": nombre_equipo, "puerto": mi_port} keys = [] # se guardaran las keys del diccionario ruta # se extraen todas las keys (para saber cuantos nodos hay en la ruta) for key in ruta_dic: keys.append(key) # se agrega el dato ruta actualizado a la lista #l[5] = json.dumps(ruta_dic) print("llaves de ruta: ", keys) # si estamos ubicados en el ultimo nodo mas cercano al cliente cambiamos el token que esta al inicio del mensaje # lo sabemos si en ruta solo quedan dos nodos: el cliente y el que tiene el servicio context_respuesta = zmq.Context() socket_respuesta = context_respuesta.socket(zmq.REQ) print(directorio) # traer la seccion de ruta para analizar cual fue el ultimo nodo agregado # enviar el puerto y el host al ultimo nodo # eliminar el ultimo nodo de la ruta #a = directorio.get(l[4]) a = ruta_dic.get(keys[-2]) # eliminar penultimo nodo de ruta (el ultimo contiene la direccion del servicio buscado) if len(keys) > 2: ruta_dic.pop(keys[-2]) l[5] = json.dumps(ruta_dic) l[0] = "s" nuevo_msm = '_'.join(l) print("nuevo mensaje:", nuevo_msm) socket_respuesta.connect("tcp://" + a['ip'] + ":" + a['puerto']) socket_respuesta.send_string(nuevo_msm) else: cliente = l[4] ruta_str = l[5] # string de ruta ruta_dic = json.loads(ruta_str) # diccionario de ruta print(ruta_dic) ruta_dic[yo] = {"ip": nombre_equipo, "puerto": mi_port} ruta_str = json.dumps(ruta_dic) l[5] = ruta_str nuevo_msm = '_'.join(l) keys = [] # se guardaran las keys del diccionario ruta # se extraen todas las keys (para saber cuantos nodos hay en la ruta) for key in ruta_dic: keys.append(key) # tenemos que verificar no replicar el mensaje a los nodos que ya estan dentro de ruta for key in directorio: if key != yo and key != cliente and key not in keys: print("yolo") info = directorio.get(key) print(info) context_replicar = zmq.Context() socket_replicar = context_replicar.socket( zmq.REQ) socket_replicar.connect("tcp://" + info['ip'] + ":" + info['puerto']) socket_replicar.send_string(nuevo_msm) elif l[0] == "r": msm_c = l[1] # operador a = directorio.get(msm_c) if a == None: adicionar(l) print("este es l", l) print(directorio) else: pass # recibir mensaje de confirmacion (servicio encontrado) elif l[0] == "s": # si queda un solo elemento en ruta: conectar directamente # sino seguir pasando el mensaje al penultimo nodo de ruta ruta_str = l[5] ruta_dic = json.loads(ruta_str) keys = [] for key in ruta_dic: keys.append(key) if len(keys) == 2: print("entrooooooo", l) # conectarse directamente aux = ruta_dic.get(l[1]) # "-" #print("entro correctamente felicitaciones !!!", aux) host = aux["ip"] port = aux["puerto"] #print("ruta: ", ruta_dic) ruta_dic.pop(l[1]) l[5] = json.dumps(ruta_dic) nuevo_msm = '_'.join(l) #print("este es el nuevo mensaje: ", nuevo_msm) context_servicio = zmq.Context() socket = context_servicio.socket(zmq.REQ) socket.connect("tcp://" + host + ":" + port) socket.send_string(nuevo_msm) # el servidor recibe conexion directa de elif len(keys) == 1: print("respondiendo...") print(l) respuesta = int(l[2]) - int(l[3]) respuesta = "resultado"+"_" + \ l[1]+"_"+l[2]+"_"+l[3]+"_" + \ str(respuesta) # "resultado_-_2_3_1" print(respuesta) aux = ruta_dic.get(l[4]) # "+" print("este es el cliente", aux) host = aux.get("ip") port = aux.get("puerto") context_servicio = zmq.Context() socket = context_servicio.socket(zmq.REQ) socket.connect("tcp://" + host + ":" + port) socket.send_string(respuesta) else: aux = ruta_dic.get(keys[-2]) # [+,-,/] host = aux["ip"] port = aux["puerto"] ruta_dic.pop(keys[-2]) # [+,/] context_servicio = zmq.Context() socket = context_servicio.socket(zmq.REQ) socket.connect("tcp://" + host + ":" + port) socket.send_string(mensaje) elif l[0] == "e": print("entro a resultado") # "resultado_-_2_3_1" print(l) print(str(l[2]) + str(l[1]) + str(l[3]) + ": " + str(l[4])) elif l[0] == "resultado": # "resultado_-_2_3_1" print(l[2] + l[1] + l[3] + ": " + l[4]) except: pass except: pass # print("ffffff")
import socket context = zmq.Context() suma = context.socket(zmq.REQ) suma.connect("tcp://localhost:8000") #avisar que el servicio esta activo nombre_equipo = str(socket.gethostname()) msm = "*"+","+nombre_equipo+","+"8003" suma.send_string(msm) acuse = suma.recv_string() print (acuse) #contexto para reply context_rep = zmq.Context() socket = context_rep.socket(zmq.REP) socket.bind("tcp://*:8003") message = socket.recv_string() print (message) l = message.split(",") print (l) respuesta = int(l[1]) * int(l[2]) print (respuesta) respuesta = str(respuesta) socket.send_string(respuesta)
async def main(): global console_out, proc, master_ip, filename my_thread_inet = Thread(target=inet_work) my_thread_inet.daemon = True my_thread_inet.start() my_thread_video = Thread(target=key_to_robot) my_thread_video.daemon = True my_thread_video.start() my_thread_video = Thread(target=test_wifi) my_thread_video.daemon = True my_thread_video.start() filename = "/autostart.py" print("Autostart file", filename) asyncio.ensure_future(run_subprocess()) await asyncio.sleep(0.001) # process = asyncio.create_subprocess_exec(*["python3", "print1.py"], stdout=slave) # print("start", process.returncode) flag_file = False # filename = "" print("Start demon") while True: # Wait for next request from client if flag_file: # print("wait file data") t = time.time() message = "" while 1: try: message = socket.recv() except: pass if message != "": break if time.time() - t > 5: break # message = message.decode("utf-8") print("filename", filename) # print("file", message) # message = zlib.decompress(message) flag_file = False if message == "": print("bad file") continue text_file = open(dir + filename, "wb") try: text_file.write(zlib.decompress(message)) except: print("error compress") pass text_file.close() try: socket.send_string("ok") except: pass continue message = "" try: message = socket.recv_string(zmq.NOBLOCK) except: pass # if len(message)>0: # print("Received request: %s" % message) await asyncio.sleep(0.001) if message == "": time.sleep(0.01) # print("message empty") continue # time.sleep(0.001) print("message", message) message = message.split("|") if message[0].find("data") >= 0: snd = "STOPED " if proc: if len(console_out) == 0: if proc.returncode == None: # print(console_out) asyncio.ensure_future(run_subprocess_read()) # print(console_out) snd = console_out if len(console_out) > 0: snd = console_out # print(len(console_out)) # if len(console_out) < 1024: # await asyncio.sleep(0.1) # print("send: "+snd) try: socket.send_string(snd) except: pass console_out = "" continue if message[0].find("stop") >= 0: # print("stop") if proc: if proc.returncode == None: # print("k1", proc.returncode) asyncio.ensure_future(run_subprocess_read()) proc.kill() # await asyncio.sleep(2) while proc: await asyncio.sleep(0.01) # print("k2",proc.returncode) console_out_summ = "" # while len(console_out)>0: # print("len", len(console_out)) # console_out_summ+=console_out # print(console_out) # console_out="" # time.sleep(0.001) # try: socket.send_string(console_out + "STOPED ") except: pass console_out = "" proc = False print("stoping", console_out) continue # break if message[0].find("ping") >= 0: try: socket.send_string(myhost + "|" + master_ip) except: pass continue if message[0].find("take") >= 0: # назначаем хозяина master_ip = message[1] print("take", master_ip) try: socket.send_string(myhost + "|" + master_ip) except: pass continue if message[0].find("drop") >= 0: # скидываем хозяина] master_ip = "0" print("drop", master_ip) try: socket.send_string(myhost + "|" + master_ip) except: pass continue if message[0].find("file") >= 0: # принимаем файл print("filename", filename) filename = message[1] try: socket.send_string("ok") except: pass # await asyncio.sleep(0.01) flag_file = True # print("zagolovok prinat") continue if message[0].find("start") >= 0: # flag_stop = False filename = message[1] print("start file", filename) if proc == False: asyncio.ensure_future(run_subprocess()) print("start ok") try: socket.send_string("start ok") except: pass else: print("already run") try: socket.send_string("already run") except: pass # process = asyncio.create_subprocess_exec(*["python3", "print1.py"], stdout=slave) # print("start", process.returncode) continue if message[0].find("exit") >= 0: print("exit") break
socket.recv() msg_type_bytes = socket.recv() msg_type = struct.unpack("<I", msg_type_bytes)[0] if msg_type == MESSAGE_TYPE_HEARTBEAT: print( 'Recieved the first heartbeat. Now keep the model container connected' ) sys.stdout.flush() sys.stderr.flush() continue if msg_type == MESSAGE_TYPE_NEW_CONTAINER: print("Recieved container info") sys.stdout.flush() sys.stderr.flush() info = {} model_name = socket.recv_string() info['model_name'] = model_name model_version = socket.recv_string() # model_version = int(model_version) info['model_version'] = model_version model_input_type = socket.recv_string() info['model_input_type'] = model_input_type rpc_version_bytes = socket.recv() rpc_version = struct.unpack("<I", rpc_version_bytes)[0] validate_rpc_version(rpc_version) print(info) sys.stdout.flush() sys.stderr.flush() # while True:
socket.connect("tcp://localhost:5556") # Subscribe to zipcode, default is NYC, 10001 zip_filter = sys.argv[1] if len(sys.argv) > 1 else "11102" # Python 2 - ascii bytes to unicode str if isinstance(zip_filter, bytes): zip_filter = zip_filter.decode('ascii') # subscribe to messaged PREFIXED with zipfilter socket.setsockopt_string(zmq.SUBSCRIBE, "") # Process 5 updates total_temp = 0 while True: string = socket.recv_string() print(string) # socket.send_string("Yo Buddy") # uid, xPos, yPos = string.split() # xPos = int(xPos) # yPos = int(yPos) # # time.sleep(2) # mouse.position = xPos, yPos # print(hex(autopy.bitmap.capture_screen().get_color(xPos, yPos))) # mouse.move(xPos, yPos) # autopy.mouse.smooth_move(xPos, yPos) # print("Average temperature for zipcode '%s' was %dF" % ( # zip_filter, total_temp / (update_nbr+1)) # )
def test_resultsServer(): """ tests pyneal.src.resultsServer """ # create settings dictionary settings = {'pynealScannerPort': port, 'pynealHost': host, 'numTimepts': 3, 'launchDashboard': False, 'seriesOutputDir': paths['testDataDir']} scanReceiver = ScanReceiver(settings) scanReceiver.daemon = True scanReceiver.start() # Set up Pyneal Scanner simulator for making a connection to the scanReceiver context = zmq.Context.instance() socket = context.socket(zmq.PAIR) socket.connect('tcp://{}:{}'.format(host, port)) while True: msg = 'hello from test pyneal scanner simulator' socket.send_string(msg) resp = socket.recv_string() if resp == msg: break # Send data to scan receiver ds = nib.load(join(paths['testDataDir'], 'testSeries.nii.gz')) ds_array = ds.get_data() ds_affine = ds.affine for volIdx in range(ds_array.shape[3]): # grab this volume from the dataset thisVol = np.ascontiguousarray(ds_array[:, :, :, volIdx]) # build header volHeader = {'volIdx': volIdx, 'dtype': str(thisVol.dtype), 'shape': thisVol.shape, 'affine': json.dumps(ds_affine.tolist()), 'TR': str(1000)} # send header as json socket.send_json(volHeader, zmq.SNDMORE) # now send the voxel array for this volume socket.send(thisVol, flags=0, copy=False, track=False) # list for response socketResponse = socket.recv_string() # test scanReceiver get functions np.testing.assert_equal(scanReceiver.get_affine(), ds_affine) np.testing.assert_equal(scanReceiver.get_slice(1,10), ds_array[:, :, 10, 1]) np.testing.assert_equal(scanReceiver.get_vol(2), ds_array[:, :, :, 2]) # test saving (then delete) scanReceiver.saveResults() os.remove(join(paths['testDataDir'], 'receivedFunc.nii.gz')) # assuming nothing crashed, shutdown scanReceiver server scanReceiver.killServer()
def getFrame(socket): frame = socket.recv_string() img = base64.b64decode(frame) npimg = np.fromstring(img, dtype=np.uint8) return cv2.rotate(cv2.imdecode(npimg, 1), cv2.ROTATE_180)