python传输文件最重要的有两步:
1).将要传输的文件的信息发送过去,包括文件包,大小以及其它信息;
2).发送端读取文件内容并发送过去,接受端将缓存里面的内容写入文件.
发送端:
from socket import *
import os
import struct
ADDR = ('192.168.1.103',8000)
BUFSIZE = 1024
filename = 'client.py'
FILEINFO_SIZE=struct.calcsize('128s32sI8s')
sendSock = socket(AF_INET,SOCK_STREAM)
sendSock.connect(ADDR)
fhead=struct.pack('128s11I',filename,0,0,0,0,0,0,0,0,os.stat(filename).st_size,0,0)
sendSock.send(fhead)
fp = open(filename,'rb')
while 1:
filedata = fp.read(BUFSIZE)
if not filedata: break
sendSock.send(filedata)
fp.close()
sendSock.close()
|
接收端:
# -*- coding: cp936 -*-
from socket import *
import struct
ADDR = ('192.168.1.103',8000)
BUFSIZE = 1024
FILEINFO_SIZE=struct.calcsize('128s32sI8s')
recvSock = socket(AF_INET,SOCK_STREAM)
recvSock.bind(ADDR)
recvSock.listen(True)
print "wait..."
conn,addr = recvSock.accept()
print "send from ",addr
fhead = conn.recv(FILEINFO_SIZE)
filename,temp1,filesize,temp2=struct.unpack('128s32sI8s',fhead)
#print filename,temp1,filesize,temp2
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(BUFSIZE)
else:
filedata = conn.recv(restsize)
if not filedata: break
fp.write(filedata)
restsize = restsize-len(filedata)
if restsize == 0: break
fp.close()
conn.close()
recvSock.close()
print "Finished"
|
代码中,将文件信息采用struct的方式传送过去.接收端接收并unpack.整个过程发送和接受各两次,这便是整个的过程.
阅读(2268) | 评论(0) | 转发(0) |