python實現用socket傳輸檔案

來源:互聯網
上載者:User
python實現用socket傳輸檔案[複製連結]
   
  電梯直達

1#

發表於 2009-4-2 10:14:19|只看該作者|倒序瀏覽

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.整個過程發送和接受各兩次,這便是整個的過程.

分享0收藏0
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.