独角兽企业重金招聘Python工程师标准>>>
发送端:#!/usr/bin/python2.7#coding=utf-8import Tkinterimport tkFileDialogfrom socket import *import structimport osdef client(filename):Addr=('127.0.0.1',8000)BUFSIZE=1024Sendsocket=socket(AF_INET,SOCK_STREAM)Sendsocket.connect(Addr)FileHead=struct.pack('128s11i',filename,0,0,0,0,0,0,0,0,os.stat(filename).st_size,0,0)Sendsocket.send(FileHead)fp=open(filename,'rb')while 1:FileData=fp.read(BUFSIZE)if not FileData: breakSendsocket.send(FileData)fp.close()Sendsocket.close()def FileOpen():r = tkFileDialog.askopenfilename(title = 'Python Tkinter',filetypes=[('All files', '*')] )filename=r.split('/')client(filename[-1])root = Tkinter.Tk()button1 = Tkinter.Button(root, text = 'File Open', height=8,width=14,bg='blue', command = FileOpen)button1.pack()root.mainloop()服务器端#!/usr/bin/python2.7# -*- coding: utf-8 -*-from socket import *import osimport structAddr=('127.0.0.1',8000)BUFSIZE=1024FileInfoSize=struct.calcsize('128s32sI8s')SocketRecv=socket(AF_INET,SOCK_STREAM)SocketRecv.bind(Addr)SocketRecv.listen(5)print "waitting ........"conn,addr=SocketRecv.accept()print "send from" ,addrFileHead=conn.recv(FileInfoSize)filename,temp1,filesize,temp2=struct.unpack('128s32sI8s',FileHead)print filename,len(filename),type(filename)print filesizefilename='new_'+filename.strip('\00')fp = open(filename,'wb')restsize=filesizewhile 1:if restsize<BUFSIZE:filedata=conn.recv(restsize)else:filedata=conn.recv(BUFSIZE)if not filedata:breakfp.write(filedata)restsize=restsize-len(filedata)if restsize==0:breakfp.close()conn.close()SocketRecv.close()print 'Finished !!!'
如果觉得《python socket文件传输》对你有帮助,请点赞、收藏,并留下你的观点哦!