python socket传文件

python传输文件最重要的有两步:

1).将要传输的文件的信息发送过去,包括文件包,大小以及其它信息;

2).发送端读取文件内容并发送过去,接受端将缓存里面的内容写入文件.

发送端:

# -*- coding: cp936 -*-

from socket import *

import os

import struct

ADDR = ('192.168.0.178',8000)

BUFSIZE = 1024

filename = 'wubi.exe'

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)

print "文件传送完毕,正在断开连接..."

fp.close()

sendSock.close()

print "连接已关闭..."

 

接收端:

# -*- coding: cp936 -*-

from socket import *

import struct

ADDR = ('192.168.0.178',8000)

BUFSIZE = 1024

FILEINFO_SIZE=struct.calcsize('128s32sI8s')

recvSock = socket(AF_INET,SOCK_STREAM)

recvSock.bind(ADDR)

recvSock.listen(True)

print "等待连接..."

conn,addr = recvSock.accept()

print "客户端已连接—> ",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

print "正在接收文件... ",

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

print "接收文件完毕,正在断开连接..."

fp.close()

conn.close()

recvSock.close()

print "连接已关闭..."

 

该程序经过实际测试可用,大家经过修改相应代码即可在本地进行测试使用。

友情提示:

用于传送比较大的文件时会比较慢,还可能照成命令行假死的情况...

你可能感兴趣的:(编程人生)