Python客户端-服务器协议通信

0 投票
0 回答
32 浏览
提问于 2025-04-12 00:13

我们有一个项目需要遵循的协议。我们被要求用Python编写服务器和客户端的代码。我已经写好了服务器和客户端的代码,但遇到了一些错误。你能帮我修正这些代码吗?下面是给我们的协议。

[在这里输入图片描述](https://i.stack.imgur.com/0maxY.png)[在这里输入图片描述](https://i.stack.imgur.com/njkgf.png)

服务器:

import socket
import os


def parse_header(header_bytes):
    # Parse header information
    message_type = (header_bytes[7] >> 7) & 0b1
    query_type = (header_bytes[7] >> 5) & 0b11
    message_id = header_bytes[7] & 0b11111
    timestamp = (header_bytes[6] << 24) | (header_bytes[5] << 16) | (header_bytes[4] << 8) | header_bytes[3]
    status_code = (header_bytes[2] >> 5) & 0b111
    body_length = header_bytes[1]
    return message_type, query_type, message_id, timestamp, status_code, body_length


def handle_client(client_socket):
    # Process message received from the client
    header = client_socket.recv(8)  # Receive 8 bytes of data for the 64-bit header
    message_type, query_type, message_id, timestamp, status_code, body_length = parse_header(header)

    if query_type == 0b00:  # Verify directory existence
        # Receive the file path from the client
        directory_length = body_length
        directory = client_socket.recv(directory_length).decode()

        # Check directory existence
        if os.path.exists(directory):
            status_code = 0b000  # Exist
        else:
            status_code = 0b001  # Not Exist

        # Send the result to the client
        header = bytes([(message_type << 7) | (query_type << 5) | message_id, (status_code << 5) | body_length])
        client_socket.send(header)

    elif query_type == 0b01:  # Check file existence
        # Receive the file path from the client
        file_length = body_length
        file_path = client_socket.recv(file_length).decode()

        # Check file existence
        if os.path.isfile(file_path):
            status_code = 0b000  # Exist
        else:
            status_code = 0b001  # Not Exist

        # Send the result to the client
        header = bytes([(message_type << 7) | (query_type << 5) | message_id, (status_code << 5) | body_length])
        client_socket.send(header)

    elif query_type == 0b10:  # Determine if an existing file has been modified after a specified timestamp
        # Receive file information from the client
        file_info_length = body_length
        file_info = client_socket.recv(file_info_length).decode()

        # Check file existence and timestamp
        file_path, timestamp = file_info.split(',')
        if os.path.isfile(file_path):
            file_timestamp = os.path.getmtime(file_path)
            if file_timestamp > int(timestamp):
                status_code = 0b010  # Changed
            else:
                status_code = 0b011  # Not Changed
        else:
            status_code = 0b001  # Not Exist

        # Send the result to the client
        header = bytes([(message_type << 7) | (query_type << 5) | message_id, (status_code << 5) | body_length])
        client_socket.send(header)

    elif query_type == 0b11:  # Identify files with a specified extension that have been modified after a given timestamp
        # Receive file extension and timestamp information from the client
        file_info_length = body_length
        file_info = client_socket.recv(file_info_length).decode()

        # Check file extension and timestamp
        file_extension, timestamp = file_info.split(',')
        matching_files = [f for f in os.listdir('.') if f.endswith(file_extension)]
        modified_files = []
        for file in matching_files:
            file_path = os.path.join('.', file)
            file_timestamp = os.path.getmtime(file_path)
            if file_timestamp > int(timestamp):
                modified_files.append(file)

        # Send the result to the client
        response_message = ','.join(modified_files)
        body_length = len(response_message)
        header = bytes([(message_type << 7) | (query_type << 5) | message_id, (status_code << 5) | body_length])
        client_socket.send(header)
        client_socket.send(response_message.encode())

    client_socket.close()  # Close the connection


def run_server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('localhost', 31369))  # Bind to the specified port
    server_socket.listen(1)  # Listen for connections

    print("Server is listening...")

    while True:
        client_socket, client_address = server_socket.accept()  # Accept the connection
        print(f"Connection accepted from {client_address}.")
        handle_client(client_socket)  # Process the connection


if __name__ == "__main__":
    run_server()

客户端:

import socket
import time

def create_header(message_type, query_type, message_id, timestamp, body_length):
    # Creating the header
    header = bytes([(message_type << 7) | (query_type << 5) | message_id, (timestamp >> 24) & 0xFF, (timestamp >> 16) & 0xFF, (timestamp >> 8) & 0xFF, timestamp & 0xFF, body_length])
    return header

def send_query(client_socket, header, body_message=""):
    # Sending the query message
    client_socket.send(header)
    if body_message:
        client_socket.send(body_message.encode())

def receive_response(client_socket):
    # Receive response from the server
    response_header = client_socket.recv(8)
    response_body_length = response_header[1]
    response_body = client_socket.recv(response_body_length).decode()
    return response_header, response_body

def run_client():
    server_address = ('localhost', 31369)
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(server_address)

    # QUERY 1: Verify directory existence
    message_type = 0b0
    query_type = 0b00
    message_id = 0b00001
    timestamp = 0  # Time in seconds, for example: int(time.time())
    path = input("Please enter the directory path to check: ")
    body_length = len(path)
    header = create_header(message_type, query_type, message_id, timestamp, body_length)
    send_query(client_socket, header, path)
    response_header, response_body = receive_response(client_socket)
    print("QUERY 1 Response Header:", response_header)
    print("QUERY 1 Response Body:", response_body)

    # QUERY 2: Check file existence
    message_type = 0b0
    query_type = 0b01
    message_id = 0b00010
    file_path = input("Please enter the file path to check: ")
    body_length = len(file_path)
    header = create_header(message_type, query_type, message_id, timestamp, body_length)
    send_query(client_socket, header, file_path)
    response_header, response_body = receive_response(client_socket)
    print("QUERY 2 Response Header:", response_header)
    print("QUERY 2 Response Body:", response_body)

    # QUERY 3: Determine if an existing file has been modified after a specified timestamp
    message_type = 0b0
    query_type = 0b10
    message_id = 0b00011
    file_path = input("Please enter the file path to check: ")
    timestamp = int(time.time())  # For example: int(time.time()) - 3600 (an hour ago)
    file_info = f"{file_path},{timestamp}"
    body_length = len(file_info)
    header = create_header(message_type, query_type, message_id, timestamp, body_length)
    send_query(client_socket, header, file_info)
    response_header, response_body = receive_response(client_socket)
    print("QUERY 3 Response Header:", response_header)
    print("QUERY 3 Response Body:", response_body)

    # QUERY 4: Identify files with a specified extension that have been modified after a given timestamp
    message_type = 0b0
    query_type = 0b11
    message_id = 0b00100
    file_extension = input("Please enter the file extension to check (e.g., .txt): ")
    timestamp = int(time.time()) - 3600  # For example: int(time.time()) - 3600 (an hour ago)
    file_info = f"{file_extension},{timestamp}"
    body_length = len(file_info)
    header = create_header(message_type, query_type, message_id, timestamp, body_length)
    send_query(client_socket, header, file_info)
    response_header, response_body = receive_response(client_socket)
    print("QUERY 4 Response Header:", response_header)
    print("QUERY 4 Response Body:", response_body)

    client_socket.close()

if __name__ == "__main__":
    run_client()

0 个回答

暂无回答

撰写回答