# -*- coding: UTF-8 -*- |
import struct |
import socket |
# python ftp服务端 |
class FtpServer( object ): |
def __init__( self , host, port): |
self .host = host |
self .port = port |
def ftp_server( self ): |
# 声明协议类型 |
ftp_server = socket.socket() |
# 绑定本地网卡(多网卡选择),端口 |
ftp_server.bind(( self .host, self .port)) |
# 监听端口 |
ftp_server.listen() # 监听 |
while True : |
print ( '等待...' ) |
conn, address = ftp_server.accept() |
while True : |
file_info = struct.calcsize( '128sl' ) |
buf = conn.recv(file_info) |
if buf: |
file_name, file_size = struct.unpack( '128sl' , buf) |
# 使用strip()删除打包时附加的多余空字符 |
file_new_name = file_name.decode().strip( '0' ) |
print ( 'start receiving...' ) |
fw = open (file_new_name, 'wb' ) |
received_size = 0 # 接收文件的大小 |
while not received_size = = file_size: |
if file_size - received_size > 1024 : |
r_data = conn.recv( 1024 ) |
received_size + = len (r_data) |
else : |
r_data = conn.recv(file_size - received_size) |
received_size = file_size |
fw.write(r_data) |
fw.close() |
if __name__ = = '__main__' : |
server = FtpServer( 'localhost' , 9999 ) |
server.ftp_server() |
# -*- coding: UTF-8 -*- |
import socket |
import os |
import struct |
# python ftp客户端 |
class FtpClient( object ): |
# 定义一个FtpClien类 |
def __init__( self , host, port): |
self .host = host |
self .port = port |
def client_push( self ): |
# 声明协议类型,同时生成socket对象 |
ftp_client = socket.socket() |
# 连接服务端 |
ftp_client.connect(( self .host, self .port)) |
while True : |
# 切换文件目录路径 |
print ( "输入文件目录路径" ) |
pwd = input ( ">>:" ).strip() |
# 列出文件名称 |
files_list = os.listdir( '{}' . format (pwd)) |
for i in files_list: |
print (i) |
file_name = input ( '输入上传的文件名:' ).strip() |
file_path = os.path.join(pwd, file_name) |
if os.path.isfile(file_path): |
file_info = struct.calcsize( '128sl' ) # 定义打包规则 |
f_head = struct.pack( '128sl' , file_name.encode( 'utf-8' ), os.stat(file_path).st_size) |
ftp_client.send(f_head) |
fo = open (file_path, 'rb' ) |
while True : |
file_data = fo.read( 1024 ) |
if not file_data: |
break |
ftp_client.send(file_data) |
fo.close() |
# 上传文件 |
ftp_client.send(file_data) |
# client.close() |
if __name__ = = '__main__' : |
client = FtpClient( 'localhost' , 9999 ) |
client.client_push() |