如何在Python中使用参数创建文件?文件传输客户端实现需求
Hey there! Let's get your file transfer client-server up and running, where the client can trigger file creation on the server via a command-line argument. Here's a complete, working implementation tailored to your needs:
server.py) First, let's finish and refine the threaded server code you started. This server handles multiple client connections simultaneously, receives the filename and file content, then creates the specified file locally:
# -*- coding: utf-8 -*- import socket from threading import Thread class ThreadedServer(Thread): def __init__(self, ip, port, sock): Thread.__init__(self) self.ip = ip self.port = port self.sock = sock print(f"New thread started for {ip}:{port}") def run(self): # Receive the filename from client first filename = self.sock.recv(1024).decode('utf-8').strip() print(f"Received request to create file: {filename}") # Stream and collect file content file_content = b"" while True: chunk = self.sock.recv(1024) if not chunk: break file_content += chunk # Write content to the target file with open(filename, 'wb') as f: f.write(file_content) print(f"Successfully created file: {filename}") self.sock.close() def main(): host = '0.0.0.0' port = 12345 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) threads = [] print(f"Server listening on {host}:{port}") while True: sock.listen(5) conn, (ip, port) = sock.accept() new_thread = ThreadedServer(ip, port, conn) new_thread.start() threads.append(new_thread) for t in threads: t.join() sock.close() if __name__ == "__main__": main()
client.py) This client takes a filename as a command-line argument, reads the file's content, and sends both the filename and content to the server:
# -*- coding: utf-8 -*- import socket import sys def main(): if len(sys.argv) != 2: print("Usage: python client.py <filename>") sys.exit(1) filename = sys.argv[1] host = 'localhost' # Replace with your server's IP if running remotely port = 12345 # Establish socket connection to server sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) # Send the filename first sock.send(filename.encode('utf-8')) # Read and stream file content to server try: with open(filename, 'rb') as f: chunk = f.read(1024) while chunk: sock.send(chunk) chunk = f.read(1024) print(f"Successfully sent file: {filename} to server") except FileNotFoundError: print(f"Error: File {filename} not found in client directory!") finally: sock.close() if __name__ == "__main__": main()
Start the server first in one terminal:
python server.pyYou'll see a message like
Server listening on 0.0.0.0:12345once it's ready.In a separate terminal, run the client with your target file as an argument:
python client.py file.txtEnsure
file.txtexists in the client's directory — the client will send its content to the server, which will create a copy offile.txtin the server's directory.
- Threading lets the server handle multiple client requests at once without blocking.
- We send the filename first, then stream content in 1024-byte chunks to handle large files efficiently.
- If running the server on a remote machine, update the
hostvariable inclient.pyto the server's public IP address.
内容的提问来源于stack exchange,提问作者Lucas Lisboa

