Home » Uncategorized » python socket 收发文件

python socket 收发文件

#发送端
# -*- coding: utf-8 -*-
import Tkinter
import tkFileDialog
from socket import *
import struct
import os
def client(filename):
    Addr=('127.0.0.1',8000)
    BUFSIZE=2048
    Sendsocket=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: 
            break
        Sendsocket.send(FileData)
    fp.close()
    Sendsocket.close()
def FileOpen():
    = 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()
#接收端
# -*- coding: utf-8 -*-
from socket import *
import os
import struct
Addr=('127.0.0.1',8000)
BUFSIZE=1024
FileInfoSize=struct.calcsize('128s32sI8s')
SocketRecv=socket(AF_INET,SOCK_STREAM)
SocketRecv.bind(Addr)
SocketRecv.listen(5)
print "waitting ........"
conn,addr=SocketRecv.accept()
print "send from" ,addr
FileHead=conn.recv(FileInfoSize)
filename,temp1,filesize,temp2=struct.unpack('128s32sI8s',FileHead)
print filename,len(filename),type(filename)
print filesize
filename='new_'+filename.strip('\00')
fp = open(filename,'wb')
restsize=filesize
while 1:
        if restsize<BUFSIZE:
            filedata=conn.recv(restsize)
        else:
            filedata=conn.recv(BUFSIZE)
        if not filedata:
            break
        fp.write(filedata)
        restsize=restsize-len(filedata)
        if restsize==0:break
fp.close()
conn.close()
SocketRecv.close()
print 'Finished !!!'