import socket
import struct
import json
import subprocess
import os class MYTCPServer:
address_family = socket.AF_INET socket_type = socket.SOCK_STREAM allow_reuse_address = False max_packet_size = 8192 coding='utf-8' request_queue_size = 5 server_dir='file_upload' def __init__(self, server_address, bind_and_activate=True):
"""Constructor. May be extended, do not override."""
self.server_address=server_address
self.socket = socket.socket(self.address_family,
self.socket_type)
if bind_and_activate:
try:
self.server_bind()
self.server_activate()
except:
self.server_close()
raise def server_bind(self):
"""Called by constructor to bind the socket.
"""
if self.allow_reuse_address:
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
self.server_address = self.socket.getsockname() def server_activate(self):
"""Called by constructor to activate the server.
"""
self.socket.listen(self.request_queue_size) def server_close(self):
"""Called to clean-up the server.
"""
self.socket.close() def get_request(self):
"""Get the request and client address from the socket.
"""
return self.socket.accept() def close_request(self, request):
"""Called to clean up an individual request."""
request.close() def run(self):
while True:
self.conn,self.client_addr=self.get_request()
print('from client ',self.client_addr)
while True:
try:
head_struct = self.conn.recv(4)
if not head_struct:break head_len = struct.unpack('i', head_struct)[0]
head_json = self.conn.recv(head_len).decode(self.coding)
head_dic = json.loads(head_json) print(head_dic)
#head_dic={'cmd':'put','filename':'a.txt','filesize':123123}
cmd=head_dic['cmd']
if hasattr(self,cmd):
func=getattr(self,cmd)
func(head_dic)
except Exception:
break def put(self,args):
file_path=os.path.normpath(os.path.join(
self.server_dir,
args['filename']
)) filesize=args['filesize']
recv_size=0
print('----->',file_path)
with open(file_path,'wb') as f:
while recv_size < filesize:
recv_data=self.conn.recv(self.max_packet_size)
f.write(recv_data)
recv_size+=len(recv_data)
print('recvsize:%s filesize:%s' %(recv_size,filesize)) tcpserver1=MYTCPServer(('127.0.0.1',8080)) tcpserver1.run() #下列代码与本题无关
class MYUDPServer: """UDP server class."""
address_family = socket.AF_INET socket_type = socket.SOCK_DGRAM allow_reuse_address = False max_packet_size = 8192 coding='utf-8' def get_request(self):
data, client_addr = self.socket.recvfrom(self.max_packet_size)
return (data, self.socket), client_addr def server_activate(self):
# No need to call listen() for UDP.
pass def shutdown_request(self, request):
# No need to shutdown anything.
self.close_request(request) def close_request(self, request):
# No need to close anything.
pass
import socket
import struct
import json
import os class MYTCPClient:
address_family = socket.AF_INET socket_type = socket.SOCK_STREAM allow_reuse_address = False max_packet_size = 8192 coding='utf-8' request_queue_size = 5 def __init__(self, server_address, connect=True):
self.server_address=server_address
self.socket = socket.socket(self.address_family,
self.socket_type)
if connect:
try:
self.client_connect()
except:
self.client_close()
raise def client_connect(self):
self.socket.connect(self.server_address) def client_close(self):
self.socket.close() def run(self):
while True:
inp=input(">>: ").strip()
if not inp:continue
l=inp.split()
cmd=l[0]
if hasattr(self,cmd):
func=getattr(self,cmd)
func(l) def put(self,args):
cmd=args[0]
filename=args[1]
if not os.path.isfile(filename):
print('file:%s is not exists' %filename)
return
else:
filesize=os.path.getsize(filename) head_dic={'cmd':cmd,'filename':os.path.basename(filename),'filesize':filesize}
print(head_dic)
head_json=json.dumps(head_dic)
head_json_bytes=bytes(head_json,encoding=self.coding) head_struct=struct.pack('i',len(head_json_bytes))
self.socket.send(head_struct)
self.socket.send(head_json_bytes)
send_size=0
with open(filename,'rb') as f:
for line in f:
self.socket.send(line)
send_size+=len(line)
print(send_size)
else:
print('upload successful') client=MYTCPClient(('127.0.0.1',8080)) client.run()

FTP上传下载--python的更多相关文章

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

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

  2. python之模块ftplib(实现ftp上传下载代码)

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块ftplib(实现ftp上传下载代码) #需求:实现ftp上传下载代码(不含错误处理) f ...

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

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

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

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

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

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

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

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

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

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

  8. C# -- FTP上传下载

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

  9. Java.ftp上传下载

    1:jar的maven的引用: 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...

随机推荐

  1. 51Nod 1089:最长回文子串 V2(Manacher算法)

    1089 最长回文子串 V2(Manacher算法)  基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题  收藏  关注 回文串是指aba.abba.cccbccc.aaa ...

  2. consul 1.2 支持service mesh

    主要说明: This release supports a major new feature called Connect that automatically turns any existing ...

  3. C语言Socket编程(计算机网络作业)

    最近我计算机网络课程要做作业了,没办法跟着老师一步一步的写C语言的代码,使用的计算就是Socket通信发送消息:代码实现的功能很简单,客户端向服务器端发送消息,服务器端接收客户端发来的消息,并且输出显 ...

  4. Mac 使用ab性能测试工具

    Mac 使用ab命令进行压测 1.在Mac中配置Apache ①启动Apache,打开终端 sudo apachectl -v 如下显示Apache的版本 sudo apachectl start 这 ...

  5. [LeetCode系列] 变序词查找问题(Anagrams)

    给定一系列词, 找出其中所有的变序词组合. Note: 变序词 - 组成字符完全相同但次序不同的单词. 如dog和god, ate和eat. 算法描述: 使用map<string, vector ...

  6. java并发回答

    java 线程安全比较重要的点:   在 java 编程中,记住这些关键点可以帮你避免一些严重的并发问题,比如条件竞争或死锁.   1).不可变对象默认是线程安全的,因为他们一旦被创建就不会被修改.比 ...

  7. php生成文字图片效果

    php生成文字图片效果最近看到php的GD功能,试着做了一个基本生成文字图片效果的代码: 显示文字图片页面:demo.php<?php$str = $_REQUEST['str'] ? $_RE ...

  8. VS编译后事件

    拷贝文件 copy /y "$(OutDir)Maticsoft.BuilderDALParam.dll" "D:\Project Area\2016-3-28" ...

  9. (转)TreeSet简单介绍与使用方法

    TreeSet简介 TreeSet是JAVA中集合的一种,TreeSet 是一个有序的集合,它的作用是提供有序的Set集合.它继承于AbstractSet抽象类,实现了NavigableSet< ...

  10. 汇编_指令_REP MOVESB 和 CLD

    先说说MOVSB(MOVe String Byte):即字符串传送指令,这条指令按字节传送数据.通过SI和DI这两个寄存器控制字符串的源地址和目标地址,比如DS:SI这段地址的N个字节复制到ES:DI ...