コード例 #1
0
def run():
    config = Config(
        config={
            "sampler": {
                "type": "const",
                "param": 1
            },
            "logging": True
        },
        service_name="chat-client",
    )
    tracer = config.initialize_tracer()
    active_span_source = FixedActiveSpanSource()
    tracer_interceptor = open_tracing_client_interceptor(
        tracer, active_span_source=active_span_source, log_payloads=True)

    channel = grpc.insecure_channel("localhost:50051")
    channel = intercept_channel(channel, tracer_interceptor)
    stub = chat_pb2_grpc.ChatStub(channel)

    response = list_messages(tracer, active_span_source, stub)
    pprint(MessageToDict(response))

    time.sleep(2)
    tracer.close()
    time.sleep(2)
コード例 #2
0
ファイル: chat_client.py プロジェクト: meffie/grpc-demos
 def __init__(self, hostname, port):
     self.running = False
     addr = '{0}:{1}'.format(hostname, port)
     self.channel = grpc.insecure_channel(addr)
     self.stub = chat_pb2_grpc.ChatStub(self.channel)
     self.messages = None  # generator
     self.send_thread = threading.Thread(target=self._post_messages)
     self.recv_thread = threading.Thread(target=self._get_messages)
     self.send_queue = queue.Queue()
     self.recv_queue = queue.Queue()
コード例 #3
0
    def run_grpc(self):
        channel = grpc.insecure_channel('localhost:50051')
        self.stub = chat_pb2_grpc.ChatStub(channel)

        receive_messages_thread = threading.Thread(
            target=self.receive_messages, daemon=True)
        receive_messages_thread.start()

        refresh_tabuleiro_thread = threading.Thread(
            target=self.RefreshTabuleiro, daemon=True)
        refresh_tabuleiro_thread.start()
コード例 #4
0
def run():
    with grpc.insecure_channel('localhost:8980') as channel:
        stub = chat_pb2_grpc.ChatStub(channel)
        threads = []
        for topic in TOPICS:
            thread = threading.Thread(target=list_messages,
                                      args=(stub, topic),
                                      daemon=True)
            thread.start()
            threads.append(thread)
        start_chatting(stub)
        for thread in threads:
            thread.join()
コード例 #5
0
    def __init__(self):
        self.username = None
        # se crea el canar grpc
        channel = grpc.insecure_channel(address + ':' + str(port))
        self.conn = rpc.ChatStub(channel)
        self.agregarCliente()
        print("\nBienvenido {}!".format(self.username))
        print("Selecciona alguna de las siguientes opciones")
        print("1. ver lista de clientes")
        print("2. enviar un mensaje a cliente")
        print("3. Mostar mis mensajes enviados")
        print("4. Salir")

        threading.Thread(target=self.__listen__for__messages,
                         daemon=True).start()

        opcion = input("Opcion: ")
        while (opcion != '4'):
            if opcion == '1':
                print('\n\nclientes conectados:')
                self.listaClientes()
            elif opcion == '2':
                print('Seleccione alguno de los siguientes clientes')
                self.listaClientes()
                clientSelect = input("Nombre del cliente receptor: ")
                message = input("Mensaje: ")
                m = chat.Mensaje()
                m.id = "1"
                m.mensaje = message
                m.timestamp = time.time()
                m.usernameEmisor = self.username
                m.usernameReceptor = clientSelect
                code = self.conn.EnviarMensaje(m)
                if code.value == 2:
                    print("el usuario no existe ")
                elif code.value == 3:
                    print("un error a ocurrido intentelo nuevamente")

            elif opcion == "3":
                self.mensajesEnviados()

            else:
                print('ingrese una opcion valida')

            print("\n\nSelecciona alguna de las siguientes opciones")
            print("1. ver lista de clientes")
            print("2. Enviar un mensaje")
            print("3. Mostar mis mensajes enviados")
            print("4. Salir")
            opcion = input("Opcion: ")
コード例 #6
0
ファイル: client.py プロジェクト: imnotjames/python-grpc-chat
def produce():
    username = '******'
    password = '******'

    with grpc.insecure_channel('localhost:8081') as channel:
        stub = chat_pb2_grpc.ChatStub(channel)

        session = stub.Login(
            chat_pb2.LoginRequest(username=username,
                                  password=password)).session

        try:
            while True:
                text = input('{} > '.format(username))

                stub.SendMessage(
                    chat_pb2.SendMessageRequest(session=session, text=text))
        except KeyboardInterrupt:
            stub.Logout(chat_pb2.LogoutRequest(session=session))
コード例 #7
0
ファイル: client.py プロジェクト: mcculleydj/chat
def main():
    """
    Run the chat client
    The listener is spawned in a thread because it can be exited via channel closure
    The post function is kept in the main thread because it is difficult to close a blocked thread (blocked by input())
    On ctrl-c, trigger the leave function, close the channel, and wait for the listener future to return
    """
    channel = grpc.insecure_channel("localhost:3000")
    stub = chat_pb2_grpc.ChatStub(channel)
    with concurrent.futures.ThreadPoolExecutor(1) as executor:
        future = executor.submit(listen, stub, args.name)
        try:
            post(stub, chat_pb2.User(name=args.name))
        except KeyboardInterrupt:
            pass
        finally:
            print("Leaving chat...")
            stub.Leave(chat_pb2.User(name=args.name))
            channel.close()
            future.result()
コード例 #8
0
ファイル: client.py プロジェクト: imnotjames/python-grpc-chat
def consume():
    username = '******'
    password = '******'

    with grpc.insecure_channel('localhost:8081') as channel:
        stub = chat_pb2_grpc.ChatStub(channel)

        session = stub.Login(
            chat_pb2.LoginRequest(username=username,
                                  password=password)).session

        try:
            while True:
                for message in stub.Stream(
                        chat_pb2.StreamRequest(session=session)):
                    print(format_message(message))

                    for stock in message.stock:
                        print(format_stock_message(message, stock))

                time.sleep(0.5)
        except KeyboardInterrupt:
            stub.Logout(chat_pb2.LogoutRequest(session=session))
コード例 #9
0
                print("")

                #print("Server >>> ", str(response.message))
                #print("")
            time.sleep(1)


current_msg_number = 0

flag_thread_stop = 0

channel = grpc.insecure_channel('localhost:5000')

stub_id_mapper = id_mapper_pb2_grpc.ID_mapperStub(channel)
stub_chat = chat_pb2_grpc.ChatStub(channel)

# Adquirir un ID para operar en la arquitectura
print("Pidiendo al server un ID...")
response = stub_id_mapper.ID_map(id_mapper_pb2.Empty())
#print("Server >>> ", response.value)
#print("")
my_id = response.value

print("Mi ID es: ", my_id)

thread = ReceiveMessages()
thread.start()

try:
    while True: