Exemplo n.º 1
0
 def _ReceiveRequest(self):
   buf = self._ReceiveBytes(4)
   num_bytes = struct.unpack("!I", buf)[0]
   buf = self._ReceiveBytes(num_bytes)
   request = messages_pb2.Request()
   request.ParseFromString(buf)
   return request
Exemplo n.º 2
0
def join_channel_request(sock, room_id):
    join_req = messages_pb2.JoinRoomRequest()
    join_req.room_id = room_id

    request = messages_pb2.Request()
    request.join_room_request.MergeFrom(join_req)

    send_message(sock, request, command_id=7)
    return get_response(sock)
Exemplo n.º 3
0
def input_request(sock, name, passw):
    in_req = messages_pb2.InRequest()
    in_req.login = name
    in_req.password = passw

    request = messages_pb2.Request()
    request.input_request.MergeFrom(in_req)

    send_message(sock, request, command_id=3)
    return get_response(sock)
Exemplo n.º 4
0
def register_request(sock, name, passw):
    register_req = messages_pb2.RegRequest()
    register_req.login = name
    register_req.password = passw

    request = messages_pb2.Request()
    request.register_request.MergeFrom(register_req)

    send_message(sock, request, command_id=1)
    return get_response(sock)
def descoberta(ip_servico,porta_servico):
    net = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # socket recebe as solicitacoes de descoberta
    net.bind(("",8000))
    request = messages_pb2.Request()
    response  = messages_pb2.Reply()
    while True:
        data, ip = net.recvfrom(2048)
        request.ParseFromString(data)
        if request.op ==  messages_pb2.CALCULADORA:
            response.ip = ip_servico
            response.port= porta_servico
            net.sendto(response.SerializeToString(),ip)
Exemplo n.º 6
0
    def send_request(self):
        """Send the Request message stored in this.req and resets
        it to default values.
        Returns the Response object received from the binary,
        or False if decoding the incoming message failed.
        """
        # Serialize message
        serialized = self.req.SerializeToString()

        # Reset the message to default values
        self.req = messages_pb2.Request()

        # Send message length
        msg_len = len(serialized)
        sent = self.s.send(msg_len.to_bytes(4, "big"))

        # Send message content
        total_sent = 0
        while total_sent < msg_len:
            sent = self.s.send(serialized[total_sent:])
            total_sent += sent

        # Receive message length
        data = b""
        while len(data) < 4:
            received = self.s.recv(4 - len(data))
            if len(received) == 0:
                raise ConnectionResetError("Connection was closed")
            data += received
        msg_len = int.from_bytes(data, "big")

        # Receive a Response message
        data = b""
        while len(data) < msg_len:
            received = self.s.recv(msg_len - len(data))
            if len(received) == 0:
                raise ConnectionResetError("Connection was closed")
            data += received

        # Try to parse the response and return it
        try:
            resp_msg = messages_pb2.Response()
            resp_msg.ParseFromString(data)
            return resp_msg

        # Return False if decoding fails
        except google.protobuf.message.DecodeError as e:
            print("DecodeError in reponse: {}".format(e))
            return False
def main():
    net = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    request = messages_pb2.Request()
    response = messages_pb2.Reply()
    net.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    net.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    flag = True
    while flag:
        op = int(
            raw_input(
                "Digite 0 para impressao, 1  Calculadora, 2 Som, 3 projetor"))
        request.op = op
        net.sendto(request.SerializeToString(), ("255.255.255.255", 8000))
        net.settimeout(4)  # seta o tempo de timeout para 4 segundos
        try:
            data, ip = net.recvfrom(2048)
            response.ParseFromString(data)
            flag = False  # para o laco se encontrar o dispositivo
        except:
            print("Dispositivos nao encontrado")
            continue

    print("Encontrado!")
    tupla = (response.ip, response.port)

    while True:
        operation = message_pb2.Request()
        operation.n1 = float(raw_input("Digite o primeiro numero"))
        op = raw_input("digite a operacao")
        operation.n2 = float(raw_input("Digite o segundo numero"))
        resposta = message_pb2.Reply()
        if op == "+":
            operation.op = message_pb2.Request.SOM
        elif op == "-":
            operation.op = message_pb2.Request.SUB
        elif op == "*":
            operation.op = message_pb2.Request.MUL
        elif op == "/":
            operation.op = message_pb2.Request.DIV

        net.sendto(operation.SerializeToString(), tupla)
        data, add = net.recvfrom(1024)
        resposta.ParseFromString(data)
        print(resposta.res)
Exemplo n.º 8
0
def main():

    address = environ.get('ADDRESS', 'localhost:50051')
    print(f"address: {address}")

    # sleep for a random amount of time to stagger requests with other clients
    random.seed()
    sleep_time = random.randint(0, 3)
    print(f"sleeping for {sleep_time}")
    time.sleep(sleep_time)

    request = messages_pb2.Request(start=0, end=100)
    with grpc.insecure_channel(address) as channel:
        stub = messages_pb2_grpc.RandomNumberGeneratorStub(channel)
        while True:
            try:
                n = stub.GetRandomNumber(request)
            except grpc.RpcError as e:
                print(f"{datetime.now()} ERROR {e.code()}: {e.details()}")
            else:
                print(f"{datetime.now()} Received: {n.num}")

            time.sleep(3)
Exemplo n.º 9
0
    def __init__(self, address="localhost", port=None, start_binary=True):
        self.req = messages_pb2.Request()

        # Get a free port number
        if port is None:
            tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            tcp.bind(("", 0))
            _, port = tcp.getsockname()
            tcp.close()

        # Start the binary
        if start_binary:
            try:
                if platform.system() == "Windows":
                    subprocess.Popen(["./bin/main.exe", "-p",
                                      str(port)],
                                     stdout=subprocess.DEVNULL)
                else:
                    subprocess.Popen(
                        ["bin/main", "-p", str(port)],
                        stdout=subprocess.DEVNULL)
            except OSError:
                print("Starting the binary failed")
                sys.exit()

        # Attempt connecting until it succeeds
        for _ in range(10):
            try:
                self.s = socket.create_connection((address, port))
                break
            except ConnectionRefusedError:
                time.sleep(0.1)
                continue

        # Set TCP_NODELAY to prevent delays when sending short messages
        self.s.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
Exemplo n.º 10
0
 def run(self):
     stub = msg.MessagesStub(self.channel)
     req = msg.Request(id=str(uuid.uuid4()), message='se ha apagado', \
     bot='Santander', datetime=str(arrow.now()))
     resp = stub.Message(req)
     print(resp)
Exemplo n.º 11
0
import messages_pb2
import ctypes
from ctypes import *

native_library = ctypes.CDLL('native_library.dll')

request = messages_pb2.Request()
for i in range(10):
  request.value.append(i)

request_blob = request.SerializeToString()
request_blob_p = ctypes.create_string_buffer(request_blob)

response_length = native_library.CalculateSquareRoot(len(request_blob), request_blob_p)
response_blob = ctypes.create_string_buffer(response_length)
native_library.RetrieveResult(response_blob)
response = messages_pb2.Response()
response.ParseFromString(response_blob)

for i in range(10):
  print str(response.value[i])