def Quit(self, request, context):
        resp_node = self.server.FindResponsible(request, context)
        room_name = request.roomname
        resp_serv = resp_node[1][1]

        if not resp_node[
                0]:  # Communicate with the server that might know who will respond the request
            for serv in resp_serv:
                try:
                    channel = grpc.insecure_channel(self.server.address + ':' +
                                                    str(serv))
                    conn = rpc.ChatSServerStub(
                        channel)  ## connection with the responsible server
                    result = conn.FindResponsible(
                        chat.FindRRequest(roomname=room_name))
                    resp_serv = self.Str_to_list_ports(result.port)
                    break
                except:
                    print("False Error Quit at", serv)

        if self.Request_port() in resp_serv:
            return self.server.Quit(request, context)

        for serv in resp_serv:
            try:
                channel = grpc.insecure_channel(self.server.address + ':' +
                                                str(serv))
                conn = rpc.ChatSServerStub(
                    channel)  ## connection with the server
                return conn.Quit(
                    chat.QuitRequest(roomname=request.roomname,
                                     nickname=request.nickname))
            except:
                print("True Error Quit at", serv)
Ejemplo n.º 2
0
def Cliente2():
    print('Cliente2: Trying to Send a message')
    for i in range(100):
        room_conn.SendMessage(chat.Note(nickname='Tester2', message=str(i)))
        print('Cliente2: Message:' + str(i) + 'sent ...')

    while True:
        for message in room_conn.ReceiveMessage(chat.EmptyResponse()):
            print(message)
    def CreateChat(self, request, context):
        print("Create chat")
        resp_node = self.server.FindResponsible(
            request,
            context)  # Fist - try to descover who will handle the request
        room_name = request.roomname  # the id of the room
        resp_serv = resp_node[1][
            1]  # list of severs that will/might know who handle
        print(resp_serv)

        # Talvez problema devido a atribuicoa resp_serv dentro do for
        if not resp_node[
                0]:  # Communicate with the server that might know who will respond the request
            for serv in resp_serv:
                try:
                    channel = grpc.insecure_channel(self.server.address + ':' +
                                                    str(serv))
                    conn = rpc.ChatSServerStub(
                        channel)  # connection with the responsible server
                    result = conn.FindResponsible(
                        chat.FindRRequest(roomname=room_name))
                    resp_serv = self.Str_to_list_ports(result.port)
                    break
                except:
                    print("False Fail Create Chat at", serv)

        # If this server is the one supposed to handle -----------------------------------------------------------------------------
        if self.Request_port() in resp_serv:
            print("I handle", request.roomname, request.password,
                  request.nickname)
            result = self.server.CreateChat(request.roomname, request.password,
                                            request.nickname)
            print(result)
            if result:
                return chat.JoinResponse(state='sucess', Port=0)
            else:
                return chat.JoinResponse(state='fail', Port=0)

        # Server knows who will handle --------------------------------------------------------------------------------------------
        print("I know who will handle")
        print("is : ", resp_serv)
        for serv in resp_serv:
            try:
                channel = grpc.insecure_channel(self.server.address + ':' +
                                                str(serv))
                conn = rpc.ChatSServerStub(
                    channel)  ## connection with the responsible server
                result = conn.CreateChat(
                    chat.CreateChatRequest(roomname=request.roomname,
                                           password=request.password,
                                           nickname=request.nickname))
                break
            except:
                print("False Fail Create Chat at", serv)

        return result
    def JoinChat(self, request, context):
        room = self.Validade_Room_Index(request.roomname, request.password)
        if room < len(self.ChatRooms):
            if not self.ChatRooms[room].validate_user(request.nickname):
                print('JoinChat;' + request.nickname + ";" + request.roomname)
                self.AuxJoinChat(room, request.nickname)
                self.state_file.stack_log('JoinChat;' + request.nickname +
                                          ";" + request.roomname)

                return chat.JoinResponse(state='sucess', Port=0)
        return chat.JoinResponse(state='fail', Port=0)
 def AddNewNode(self, request, context):
     others = self.server.AddNewNode(request, context)
     for tupla in others:  # each tupla is an id and a list of ports
         for node in tupla[1]:  # member 1 is the list of ports
             try:
                 channel = grpc.insecure_channel(self.server.address + ':' +
                                                 str(node))
                 conn = rpc.ChatSServerStub(
                     channel)  ## connection with the responsible server
                 conn.AddNewNode(
                     chat.NewNodeReq(n_id=request.n_id, port=request.port))
             except:
                 print("Fail on AddNewNode at", node)
     return chat.EmptyResponse()
    def ReceiveMessage(self, request, context):
        print("Send it all")
        resp_node = self.server.FindResponsible(request, context)
        room_name = request.roomname
        resp_serv = resp_node[1][1]

        if not resp_node[
                0]:  # Communicate with the server that might know who will respond the request
            for serv in resp_serv:
                try:
                    channel = grpc.insecure_channel(self.server.address + ':' +
                                                    str(serv))
                    conn = rpc.ChatSServerStub(
                        channel)  ## connection with the responsible server
                    result = conn.FindResponsible(
                        chat.FindRRequest(roomname=room_name))
                    resp_serv = self.Str_to_list_ports(result.port)
                except:
                    print("False Fai Receive Message at", serv)

        if self.Request_port() in resp_serv:
            lastindex = 0
            aux = None
            while not aux:
                aux = self.server.Validade_User(request.roomname,
                                                request.nickname)
            if aux != None:
                while True:
                    while lastindex < len(aux.Chats):
                        n = aux.Chats[lastindex]
                        n = chat.Note(roomname=request.roomname,
                                      nickname=n['nickname'],
                                      message=n['message'])
                        lastindex += 1
                        yield n
        print("What")
        for serv in resp_serv:
            try:
                channel = grpc.insecure_channel(self.server.address + ':' +
                                                str(serv))
                conn = rpc.ChatSServerStub(
                    channel)  ## connection with the server
                for note in conn.ReceiveMessage(
                        chat.First(roomname=request.roomname,
                                   nickname=request.nickname)):
                    yield note
                break
            except:
                print("Error Receive Message at", serv)
    def FindResponsible(self, request, context):
        resp_node = self.server.FindResponsible(request, context)
        room_name = request.roomname  # the name of the room
        resp_serv = resp_node[1][
            1]  # list of severs that will/might know who handle

        if resp_node[0]:
            return chat.FindRResponse(port=self.List_ports_to_str(resp_serv))

        for serv in resp_serv:
            try:
                channel = grpc.insecure_channel(self.server.address + ':' +
                                                str(serv))
                conn = rpc.ChatSServerStub(
                    channel)  ## connection with the responsible server
                return conn.FindResponsible(
                    chat.FindRRequest(roomname=room_name))
            except:
                print("Fail FindResponsible at", serv)
    def SendMessage(self, request, context):
        aux = self.Validade_User_Index(request.roomname, request.nickname)
        print(aux)
        if aux < len(self.ChatRooms):
            print('Message;' + request.nickname + ";" + request.roomname +
                  ";" + request.message)
            self.AuxSendMessage(aux, request.nickname, request.roomname,
                                request.message)
            self.state_file.stack_log('Message;' + request.nickname + ";" +
                                      request.roomname + ";" + request.message)

        return chat.EmptyResponse()
    def Quit(self, request, context):
        aux = self.Validade_User(request.roomname, request.nickname)
        if aux != None:
            print('LeftChat;' + request.nickname + ";" + request.roomname)
            self.state_file.stack_log('LeftChat;' + request.nickname + ";" +
                                      request.roomname)
            aux.Chats.append({
                'nickname': request.nickname,
                'message': request.nickname + ' quited chat room;'
            })
            aux.Nicknames.remove(request.nickname)

            return chat.EmptyResponse()
 def ReceiveMessage(self, request, context):
     print("Rcv")
     lastindex = 0
     aux = self.Validade_User(request.roomname, request.nickname)
     if aux != None:
         while True:
             while lastindex < len(aux.Chats):
                 n = aux.Chats[lastindex]
                 n = chat.Note(roomname=request.roomname,
                               nickname=n['nickname'],
                               message=n['message'])
                 lastindex += 1
                 yield n
    def Quit(self):
        q = chat.QuitRequest(roomname=self.Roomname, nickname=self.Nickname)
        for i in range(trys):
            try:
                self.conn.Quit(q)
                break
            except Exception as e:
                print("Quit")
                print(e)
                self.new_channel()

        self.Roomname = ''
        self.Nickname = ''
 def Send_message(self, Message):
     if Message != '':
         n = chat.Note(roomname=self.Roomname,
                       nickname=self.Nickname,
                       message=Message)
         for i in range(trys):
             try:
                 self.conn.SendMessage(n)
                 break
             except Exception as e:
                 print("Send")
                 print(e)
                 self.new_channel()
 def __listen_for_messages(self):
     print("Listen")
     for i in range(trys):
         try:
             for note in self.conn.ReceiveMessage(
                     chat.First(roomname=self.Roomname,
                                nickname=self.Nickname)):
                 self.chats.append(note)
             break
         except Exception as e:
             print("Receive")
             print(e)
             self.new_channel()
    def go_online(self):
        # Colocar para os nos adicionarem o main server a sua table e requisitarem a adicao deles no main server table
        if self.id != 0:
            main_servers = [11904, 11936, 11968, 12000]
            for serv in main_servers:
                self.route_table.add_node(0, serv)
                channel = grpc.insecure_channel(self.address + ':' + str(serv))
                conn = rpc.ChatSServerStub(channel)
                print("send", self.id, self.Request_port)
                conn.AddNewNode(
                    chat.NewNodeReq(n_id=self.id, port=self.Request_port))

        server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
        rpc.add_ChatSServerServicer_to_server(ChatServer(self), server)
        print('Starting server, Listenning ...')
        server.add_insecure_port('[::]:' + str(self.Request_port))
        server.start()
        server.wait_for_termination()
    def Join_to_chatRoom(self, Roomname, Password, Nickname):
        for i in range(trys):
            try:
                response = self.conn.JoinChat(
                    chat.JoinChatRequest(roomname=Roomname,
                                         password=Password,
                                         nickname=Nickname))
                break
            except:
                self.new_channel()

        print(response.state)
        if response.state == 'sucess':
            self.Nickname = Nickname
            self.Roomname = Roomname
            self.chats.clear(
            )  ## remove any old chat that could be in the chat list
            self.start_Listenner()
            return True
        else:
            return False
    def Create_chatRoom(self, Roomname, Password, Nickname):
        for i in range(trys):
            try:
                response = self.conn.CreateChat(
                    chat.CreateChatRequest(roomname=Roomname,
                                           password=Password,
                                           nickname=Nickname))
                break
            except Exception as e:
                print("Create")
                print(e)
                self.new_channel()

        if response.state == 'sucess':
            print('Sucess')
            self.Nickname = Nickname
            self.Roomname = Roomname
            self.chats.clear()
            self.start_Listenner()
            print('Time to fail')
            return True
        else:
            return False