Python Socket传输文件示例
作者:爱做梦的鱼 时间:2023-10-18 17:19:00
发送端可以不停的发送新文件,接收端可以不停的接收新文件。
例如:发送端输入:e:\visio.rar,接收端会默认保存为 e:\new_visio.rar,支持多并发,具体实现如下;
接收端:
方法一:
#-*- coding: UTF-8 -*-
import socket,time,SocketServer,struct,os,thread
host='192.168.50.74'
port=12307
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #定义socket类型
s.bind((host,port)) #绑定需要监听的Ip和端口号,tuple格式
s.listen(1)
def conn_thread(connection,address):
while True:
try:
connection.settimeout(600)
fileinfo_size=struct.calcsize('128sl')
buf = connection.recv(fileinfo_size)
if buf: #如果不加这个if,第一个文件传输完成后会自动走到下一句
filename,filesize =struct.unpack('128sl',buf)
filename_f = filename.strip('\00')
filenewname = os.path.join('e:\\',('new_'+ filename_f))
print 'file new name is %s, filesize is %s' %(filenewname,filesize)
recvd_size = 0 #定义接收了的文件大小
file = open(filenewname,'wb')
print 'stat receiving...'
while not recvd_size == filesize:
if filesize - recvd_size > 1024:
rdata = connection.recv(1024)
recvd_size += len(rdata)
else:
rdata = connection.recv(filesize - recvd_size)
recvd_size = filesize
file.write(rdata)
file.close()
print 'receive done'
#connection.close()
except socket.timeout:
connection.close()
while True:
connection,address=s.accept()
print('Connected by ',address)
#thread = threading.Thread(target=conn_thread,args=(connection,address)) #使用threading也可以
#thread.start()
thread.start_new_thread(conn_thread,(connection,address))
s.close()
方法二:
#-*- coding: UTF-8 -*-
import socket,time,SocketServer,struct,os
host='192.168.50.74'
port=12307
ADDR=(host,port)
class MyRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
print('connected from:', self.client_address)
while True:
fileinfo_size=struct.calcsize('128sl') #定义文件信息。128s表示文件名为128bytes长,l表示一个int或log文件类型,在此为文件大小
self.buf = self.request.recv(fileinfo_size)
if self.buf: #如果不加这个if,第一个文件传输完成后会自动走到下一句
self.filename,self.filesize =struct.unpack('128sl',self.buf) #根据128sl解包文件信息,与client端的打包规则相同
print 'filesize is: ',self.filesize,'filename size is: ',len(self.filename) #文件名长度为128,大于文件名实际长度
self.filenewname = os.path.join('e:\\',('new_'+ self.filename).strip('\00')) #使用strip()删除打包时附加的多余空字符
print self.filenewname,type(self.filenewname)
recvd_size = 0 #定义接收了的文件大小
file = open(self.filenewname,'wb')
print 'stat receiving...'
while not recvd_size == self.filesize:
if self.filesize - recvd_size > 1024:
rdata = self.request.recv(1024)
recvd_size += len(rdata)
else:
rdata = self.request.recv(self.filesize - recvd_size)
recvd_size = self.filesize
file.write(rdata)
file.close()
print 'receive done'
#self.request.close()
tcpServ = SocketServer.ThreadingTCPServer(ADDR, MyRequestHandler)
print('waiting for connection...' )
tcpServ.serve_forever()
发送端:
#-*- coding: UTF-8 -*-
import socket,os,struct
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('192.168.50.74',12307))
while True:
filepath = raw_input('Please Enter chars:\r\n')
if os.path.isfile(filepath):
fileinfo_size=struct.calcsize('128sl') #定义打包规则
#定义文件头信息,包含文件名和文件大小
fhead = struct.pack('128sl',os.path.basename(filepath),os.stat(filepath).st_size)
s.send(fhead)
print 'client filepath: ',filepath
# with open(filepath,'rb') as fo: 这样发送文件有问题,发送完成后还会发一些东西过去
fo = open(filepath,'rb')
while True:
filedata = fo.read(1024)
if not filedata:
break
s.send(filedata)
fo.close()
print 'send over...'
#s.close()
来源:http://www.cnblogs.com/dreamer-fish/p/5501924.html
标签:python,socket
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python中requests库的学习方法详解
2022-10-13 07:32:36
![](https://img.aspxhome.com/file/2023/5/134835_0s.png)
PHP单例模式Singleton Pattern的原理与实现介绍
2023-05-26 13:33:28
关于JSON以及JSON在PHP中的应用技巧
2023-11-16 00:03:38
Python基于requests实现模拟上传文件
2023-09-30 01:42:05
![](https://img.aspxhome.com/file/2023/4/85064_0s.png)
python用matplotlib可视化绘图详解
2022-04-20 02:38:42
![](https://img.aspxhome.com/file/2023/7/72067_0s.png)
laravel执行php artisan migrate报错的解决方法
2024-06-05 09:44:39
![](https://img.aspxhome.com/file/2023/6/122496_0s.jpg)
python区块链创建多个交易教程
2021-05-28 13:40:42
Python中property属性实例解析
2022-02-04 20:38:12
asp.net生成Excel并导出下载五种实现方法
2023-07-06 11:01:16
![](https://img.aspxhome.com/file/2023/9/77189_0s.jpg)
python openCV实现摄像头获取人脸图片
2021-08-16 08:21:03
![](https://img.aspxhome.com/file/2023/5/68475_0s.jpg)
使用Python进行数独求解详解(一)
2023-12-25 09:39:20
![](https://img.aspxhome.com/file/2023/5/130945_0s.jpg)
网页设计中的对比原则与接近性原则
2010-03-30 14:51:00
![](https://img.aspxhome.com/file/UploadPic/20103/30/1121120-49s.jpg)
利用OpenCV+Tensorflow实现的手势识别
2022-04-03 02:12:33
![](https://img.aspxhome.com/file/2023/3/128503_0s.png)
Python人脸识别第三方库face_recognition接口说明文档
2022-07-12 04:15:37
php在windows环境下获得cpu内存实时使用率(推荐)
2023-11-15 04:44:23
关于网站地图
2011-01-06 12:14:00
![](https://img.aspxhome.com/file/UploadPic/20111/6/116-64s.jpg)
关于Python OS模块常用文件/目录函数详解
2023-07-04 06:30:06
![](https://img.aspxhome.com/file/2023/9/71509_0s.png)
MySQL5.7.21解压版安装详细教程图解
2024-01-25 10:23:57
![](https://img.aspxhome.com/file/2023/5/128075_0s.png)
python中property属性的介绍及其应用详解
2022-09-26 03:21:36
python之array赋值技巧分享
2021-11-23 17:16:55