Exemple #1
0
def request_download(file_id, selector):
    global download_manager
    md5 = None
    for value in remote_files.values():
        if value.indice == file_id:
            md5 = value.md5
            filename = list(value.locations.values())[0][0]
            download_manager = (filename, {})
            break
    size = remote_files[md5].size // len(remote_files[md5].locations)
    remaining_data = remote_files[md5].size % len(remote_files[md5].locations)
    start = 0
    index = 1
    for ip in remote_files[md5].locations.keys():
        msg = 'DOWNLOAD\n'
        msg += md5 + '\n'
        msg += str(start) + '\n'
        if index == len(remote_files[md5].locations):
            size += remaining_data
        msg += str(size) + '\n'
        start += size
        sock = start_connection(ip, selector)
        download_manager[1][sock] = [[index], [], 1, msg]
        send_msg(sock, msg.encode('UTF-8'))
        index += 1
Exemple #2
0
def search_for_game(s):
    ''' Initiate game search '''
    send_msg(s, SEARCH)

    # TODO: Implement differences for Part 2
    response = s.recv(1024).decode()

    if response == OK:
        print("Searching for game ...")
Exemple #3
0
def finish_game(s, message):
    print_gameboard(s, message)
    if message.split()[0] == "END":
        print("The game has ended. " + message.split()[1] + "won!")
    elif message.split()[0] == "TIE":
        print("The game has ended. Tie game.")
    else:
        exit_error(s, message)

    # Send OK to server
    send_msg(s, OK)

    # TODO: handle new game after finishing
    print("")
Exemple #4
0
def re_request_download(socket):
    global download_manager
    conn = download_manager[1].pop(
        socket
    )  # Eliminamos la conexión del socket del peer que no respondió lo que le pedimos
    if len(download_manager[1]) > 0:
        new_responsible_sock = min(download_manager[1],
                                   key=download_manager[1].get)
        download_manager[1][new_responsible_sock][2] += 1
        download_manager[1][new_responsible_sock][0].append(conn[0][0])
        send_msg(new_responsible_sock, conn[3].encode(
            'UTF-8'))  # Le reasignamos el mensaje que no nos dieron al nuevo
        return True
    else:
        return False
Exemple #5
0
def service_connection(key, mask):
    socket = key.fileobj
    if mask & selectors.EVENT_READ:
        recv_data = recv_msg(socket)
        if recv_data:
            data = recv_data.decode('utf-8')
            # Me pidieron chunk
            if data.splitlines()[0] == "DOWNLOAD":
                response = telnet.process_download(data)
                send_msg(socket, response)
                print('Chunk enviado')

            # Error en pedido de descarga
            elif data.splitlines()[0] == "DOWNLOAD FAILURE":
                success = telnet.re_request_download(socket)
                if not success:
                    telnet_connections[0].send(b'DESCARGA FALLIDA\n')
                sel.unregister(socket)
                socket.close()

            else:
                download_manager = telnet.process_file_chunk(socket, data)
                if download_manager:
                    # Escribimos el archivo en disco
                    file_path = os.getcwd() + "/files/" + download_manager[0]
                    conns = []
                    for conn in download_manager[1].values():
                        for i in range(len(conn[0])):
                            conns.append([conn[0][i], conn[1][i]])

                    with open(file_path, "w") as f:
                        chunks = sorted(conns, key=lambda x: x[0])
                        for chunk in chunks:
                            f.write(chunk[1])
                        telnet_connections[0].send(b'DESCARGA EXITOSA\n')

                    # Cerramos conexiones
                    for sock in download_manager[1].keys():
                        sel.unregister(sock)
                        sock.close()

        else:
            print(colored('Cerrando conexión.', 'red'))
            sel.unregister(socket)
            socket.close()
Exemple #6
0
def game_login(s, name):
    ''' This command takes one argument, your name. A player name is a userid that uniquely
    identifies a player. Your name is entered with this command and is sent to the server.
    Return True if login success, False if login failed.'''
    # Send message to server
    send_msg(s, LOGIN(name))

    # Receive response message from server
    response = s.recv(1024).decode()

    # Check response from server
    if response == OK:
        print("Logged in as " + name)
        return True
    elif response == ERR401:
        print("Login Failed. Try another name.")
        return False
    else:
        # Message from server is not recognized, close connection and exit
        exit_error(s, response)
Exemple #7
0
def game_exit(s):
    '''The player exits the server. It takes no argument. A player can issue this 
    command at any time. 
    Close the client socket and exit the program.'''
    # Send exit message to server
    send_msg(s, EXIT)

    # Receive confirmation
    responses = get_messages(s)

    for response in responses:
        if response == OK:
            # Close socket and exit client program
            print("Logging out.")
            s.close()
            sys.exit()
        elif response == QUIT:
            send_msg(s, QUIT)
            s.close()
            sys.exit()
        else:
            # Message from server is not recognized, close connection and exit
            exit_error(s, response)
Exemple #8
0
def game_place(s, n):
    '''This command issues a move. It takes one argument n, which is between 1 and 9 inclusive.
    It identify a cell that the player chooses to occupy at this move. 
    If all is well, the new game state is received from the server and displayed.'''
    # Send place message to server
    send_msg(s, PLACE(n))

    # Receive response message from server
    responses = get_messages(s)
    if quit_received(responses):
        handle_exit(s)
    response = responses[0]

    if response.split()[0] == "GAME":
        display_game_state(s, response)
    elif response.split()[0] in ["END", "TIE"]:
        finish_game(s, response)
        # Search for new game after finishing
        search_for_game(s)
    elif response.split()[1] == "ERROR":
        place_error(s, response)
    else:
        # Message from server is not recognized, close connection and exit
        exit_error(s, response)