You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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()
运行步骤
  1. Start the server first in one terminal:

    python server.py
    

    You'll see a message like Server listening on 0.0.0.0:12345 once it's ready.

  2. In a separate terminal, run the client with your target file as an argument:

    python client.py file.txt
    

    Ensure file.txt exists in the client's directory — the client will send its content to the server, which will create a copy of file.txt in the server's directory.

Key Details
  • 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 host variable in client.py to the server's public IP address.

内容的提问来源于stack exchange,提问作者Lucas Lisboa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:27:00