socket实现ftp文件的上传和下载

server端代码:

import socket
import json
import struct
import os
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.bind(('127.0.0.1', 8021)) soc.listen(5)
# 上传函数
def uploading_file():
while True:
try:
ftp_dir = r'F:\shpython11\pycharmwork\first_project\study_start\day32\ftp_dir'
if not os.path.isdir(ftp_dir): # 这个是作为我们上传了之后的文件放在这个位置,你改成自己本地的
os.mkdir(ftp_dir)
head_bytes_len = conn.recv(4) # 拿到struct后的头长度 head_len = struct.unpack('i', head_bytes_len)[0] # 取出真正的头长度 # 拿到真正的头部内容
head_bytes = conn.recv(head_len)
# 反序列化后取出头
head = json.loads(head_bytes) file_name = head['file_name']
file_path = os.path.join(ftp_dir,file_name)
data_len = head['data_len']
with open(file_path, 'wb') as fw:
while data_len > 1024:
fw.write(conn.recv(1024))
data_len -= 1024
else:
fw.write(conn.recv(data_len))
conn.send(f'上传文件 {file_name} 成功'.encode('utf8'))
except Exception:
break while True:
print('等待客户端连接。。。')
conn, addr = soc.accept()
print('客户端已连接:', addr)
choice = conn.recv(1).decode('utf8')
if choice == 'q':
break
if choice == '1':
print('客户端选择了ftp上传服务')
uploading_file()
elif choice == '2':
print('客户端选择了ftp下载服务')
while True:
try:
ftp_dir = r'F:\shpython11\pycharmwork\first_project\study_start\day32\ftp_dir'
if not os.path.isdir(ftp_dir): # 这个是作为我们上传了之后的文件放在这个位置,你改成自己本地的
os.mkdir(ftp_dir)
file_list = os.listdir(ftp_dir)
head = {'file_list': file_list}
head_bytes = json.dumps(head).encode('utf8')
head_bytes_len = struct.pack('i', len(head_bytes)) conn.send(head_bytes_len)
conn.send(head_bytes) client_head_bytes_len = conn.recv(4) client_head_len = struct.unpack('i', client_head_bytes_len)[0]
client_head_bytes = conn.recv(client_head_len)
client_head = json.loads(client_head_bytes)
choice = client_head['choice']
file_name = file_list[int(choice)] file_path = os.path.join(ftp_dir, file_name) with open(file_path, 'rb') as fr:
data = fr.read() server_head = {'data_len': len(data), 'file_name': file_name} # 自定义头
server_head_bytes = json.dumps(server_head).encode('utf8')
server_head_bytes_len = struct.pack('i', len(server_head_bytes)) conn.send(server_head_bytes_len)
conn.send(server_head_bytes)
conn.send(data)
conn.send(f'下载文件 {file_name} 成功'.encode('utf8')) except Exception:
break conn.close()
soc.clone()

client端代码:

import socket
import os
import struct
import json
client_soc = socket.socket() client_soc.connect(('127.0.0.1',8021)) # 获取文件夹下的文件
def get_file_list(file_path):
if os.path.exists(file_path):
if os.path.isfile(file_path):
return True,file_path
else:
file_list = os.listdir(file_path)
if file_list==[]:
return False,'当前文件夹为空,请重新选择'
else:
return True,file_list
else:
return False,'你输入的文件路径不对' # 上传函数
def uploading_file():
print('欢迎进入ftp文件上传系统')
while True:
dir_path = input('请输入文件所在的文件夹路径或文件路径(输入q退出):') if dir_path == 'q':
print('你选择了退出上传系统')
break
flag, dir_list = get_file_list(dir_path)
if flag:
if os.path.isfile(dir_path):
file_name = dir_path.split('\\')[-1]
file_path = dir_path
else:
for ind, file in enumerate(dir_list):
print(f'文件编号:{ind} 对应的文件名为:{file}')
choice = input('请输入文件编号进行上传:').strip()
choice = int(choice)
file_name = dir_list[choice]
file_path = os.path.join(dir_path, file_name) with open(file_path,'rb') as fr:
data = fr.read()
head = { 'data_len': len(data),'file_name':file_name} # 自定义头
head_bytes = json.dumps(head).encode('utf8')
head_bytes_len = struct.pack('i',len(head_bytes)) client_soc.send(head_bytes_len)
client_soc.send(head_bytes)
client_soc.send(data)
msg = client_soc.recv(1024)
print(msg.decode('utf8'))
else:
print('你输入的文件路径不存在') # 下载函数
def download():
print('欢迎来到ftp下载系统')
head_bytes_len = client_soc.recv(4)
head_len = struct.unpack('i', head_bytes_len)[0]
head_bytes = client_soc.recv(head_len)
head = json.loads(head_bytes)
file_list = head['file_list']
if file_list == []:
print('当前ftp中无文件可下载,等待上传中')
else:
print('当前ftp中有如下文件')
for ind,file in enumerate(file_list):
print(f'文件编号:{ind} 对应的文件名为:{file}')
choice = input('请选择要下载文件的编号:')
choice_head = {'choice':choice} # 自定义头 choice_head_bytes = json.dumps(choice_head).encode('utf8') choice_head_bytes_len = struct.pack('i', len(choice_head_bytes))
client_soc.send(choice_head_bytes_len)
client_soc.send(choice_head_bytes) # 接收用户传递过来的文件
client_head_bytes_len = client_soc.recv(4) # 拿到struct后的头长度 client_head_len = struct.unpack('i', client_head_bytes_len)[0] # 取出真正的头长度
# 拿到真正的头部内容
client_head_bytes = client_soc.recv(client_head_len)
# 反序列化后取出头
client_head = json.loads(client_head_bytes)
file_name = client_head['file_name']
data_len = client_head['data_len'] with open(file_name, 'wb') as fw:
while data_len > 1024:
fw.write(client_soc.recv(1024))
data_len -= 1024
else:
fw.write(client_soc.recv(data_len))
msg = client_soc.recv(1024)
print(msg.decode('utf8')) while True:
msg = '''
1.文件上传
2.文件下载
q.退出系统
'''
print(msg)
choice = input('请做出你的选择:').strip()
client_soc.send(choice.encode('utf8'))
if choice == 'q':
print('你选择了退出系统')
break
if choice == '1':
uploading_file() elif choice == '2':
download()

socket实现ftp上传下载的更多相关文章

  1. socket实现FTP上传下载功能

    '''服务器端''' 1 _author__ = "Dbass" import socketserver import json,os class MyTCPHandler(soc ...

  2. python之实现ftp上传下载代码(含错误处理)

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之实现ftp上传下载代码(含错误处理) #http://www.cnblogs.com/kait ...

  3. FTP上传下载文件(函数简易版)

    FTP上传下载文件(函数简易版) # 服务端 import socket import json import hashlib import struct import os user_dic = { ...

  4. JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)

    package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...

  5. windows系统下ftp上传下载和一些常用命令

    先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单, ...

  6. windows下ftp上传下载和一些常用命令

    先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单, ...

  7. FTP上传下载工具(FlashFXP) v5.5.0 中文版

    软件名称: FTP上传下载工具(FlashFXP) 软件语言: 简体中文 授权方式: 免费试用 运行环境: Win 32位/64位 软件大小: 7.4MB 图片预览: 软件简介: FlashFXP 是 ...

  8. 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

    前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上 ...

  9. C# -- FTP上传下载

    C# -- FTP上传下载 1. C#实现FTP下载 private static void TestFtpDownloadFile(string strFtpPath, string strFile ...

随机推荐

  1. java架构之路-(MQ专题)RocketMQ从入坑到集群详解

    这次我们来说说我们的RocketMQ的安装和参数配置,先来看一下我们RocketMQ的提出和应用场景吧. 早在2009年,阿里巴巴的淘宝第一次提出了双11购物狂欢节,但是在2009年,服务器无法承受到 ...

  2. Java 中文数字转换为阿拉伯数字

    贴出代码,方便学习交流,稍后放出镜像问题的代码 package com.thunisoft.cail.utils; import com.sun.istack.internal.NotNull; im ...

  3. [考试反思]1013csp-s模拟测试72:距离

    最近总是这个样子. 看上去排名好像还可以,但是实际上离上面的分差往往能到80分,但是身后的分差其实只有10/20分. 比上不足,比下也不怎么的. 所以虽然看起来没有出rank10,但是在总分排行榜上却 ...

  4. 复制/etc/profile至/tmp/目录,用查找替换命令删除/tmp/profile文件中的 行首的空白字符及在vim中设置tab缩进为4个字符

    1.复制/etc/profile至/tmp/目录,用查找替换命令删除/tmp/profile文件中的 行首的空白字符 在命令模式下,使用正则表达式匹配 行首有空白字符行的模式:^[[:space:]] ...

  5. Redis集群--Redis集群之哨兵模式

    echo编辑整理,欢迎转载,转载请声明文章来源.欢迎添加echo微信(微信号:t2421499075)交流学习. 百战不败,依不自称常胜,百败不颓,依能奋力前行.--这才是真正的堪称强大!!! 搭建R ...

  6. 控制UI界面

    在android中,一共有四种方式. 第一种:使用XML布局文件控制UI界面 关键步骤有2个: 1.在Android应用的res/layout目录下编写,创建一个项目,eclipse会自动生成一个xm ...

  7. CSS尺寸样式属性

    尺寸样式属性介绍 属性 值 含义 height auto:自动,浏览器会自动计算高度length:使用px定义高度%:基于包含它的块级对象的百分比高度 设置元素高度 width 同上 设置元素的宽度 ...

  8. 用大写字母输入 Linux 命令,实现以 sudo 用户权限运行

    我们知道,一些 Linux 命令是要通过 sudo 权限才能运行的,这需要我们每次使用这些命令时在前面加一个 sudo ,十分繁琐.今天给大家介绍一个好用的工具 SUDO ,它只需要我们用大写字母键入 ...

  9. nyoj 811-变态最大值 (max)

    811-变态最大值 内存限制:64MB 时间限制:1000ms 特判: No 通过数:6 提交数:15 难度:1 题目描述: Yougth讲课的时候考察了一下求三个数最大值这个问题,没想到大家掌握的这 ...

  10. 【集合系列】- 深入浅出的分析TreeMap

    一.摘要 在集合系列的第一章,咱们了解到,Map的实现类有HashMap.LinkedHashMap.TreeMap.IdentityHashMap.WeakHashMap.Hashtable.Pro ...