python从服务器下载文件_如何用Python从本地服务器下载文件

下面的示例演示如何通过tcp从服务器下载文件。

客户代码:import socket

import os

HOST = 'localhost'

PORT = 1024

downloadDir = "/tmp"

filename = raw_input('Enter your filename: ')

socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

socket1.connect((HOST, PORT))

socket1.send(filename)

with open(os.path.join(downloadDir, filename), 'wb') as file_to_write:

while True:

data = socket1.recv(1024)

if not data:

break

file_to_write.write(data)

file_to_write.close()

socket1.close()

服务器代码:import socket

HOST = 'localhost'

PORT = 1024

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

socket.bind((HOST, PORT))

socket.listen(1)

while (1):

conn, addr = socket.accept()

reqFile = conn.recv(1024)

with open(reqFile, 'rb') as file_to_send:

for data in file_to_send:

conn.sendall(data)

conn.close()

socket.close()

注意:服务器代码不健壮,当文件不存在时将崩溃。你应该根据你的需要修改上面的例子。

你可能感兴趣的:(python从服务器下载文件)