Python TCP Socket Transfer file

Source: Internet
Author: User

"Test Environment"

Os:windows x64python:3.6.3


"Server.py"

#encoding: utf-8#author: walker#date:  2017-12-01  #summary:  Create a tcp  with a socket Server to receive Files  import os, timeimport socketimport structcur_dir_fullpath =  Os.path.dirname (Os.path.abspath (__file__)) host =  ' 127.0.0.1 ' port = 6789bufsize =  8196FmtHead =  ' 256sHL ' #L决定单个文件必须小于4GFmtHeadLen  = struct.calcsize (fmthead) dstroot  = os.path.join (cur_dir_fullpath,  ' output ') #目标目录StartTime  = time.time () #开始时间def   Procall (): Cnt = 0filesizetotal = 0sockserver = socket.socket (Socket.AF_INET,  socket. Sock_stream) Sockserver.bind ((Host, port)) print (' listen prot %d  .... '  % port) Sockserver.listen (1) sock, addr = sockserver.accept () print (' local: %s:%d '  %  ( Sock.getsockname ())) print (' client: %s:%d '  % addr) while true: #接收数据包头 (relative path, relative path length, File size) Pkghead = sock.recv(Fmtheadlen) Relpath, relpathlen, filesize = struct.unpack (FmtHead, pkgHead) RelPath  = relpath.decode (' UTF8 ') [0:relpathlen]if relpath ==  ' over '  and filesize  == 0:print (' all file recv over! ') Breakpathfile = os.path.join (Dstroot, relpath) dstdir = os.path.dirname (pathfile) if  not os.path.exists (Dstdir): Os.makedirs (Dstdir) with open (pathfile, mode= ' WB ')  as  f:recvsize = 0# The amount of data received from a single file while true:if recvsize >= filesize:breakbufsize  = bufsizeif filesize - recvsize < bufsize: #剩余数据量小于BufSizebufSize  = &NBSP;FILESIZE&NBSP;-&NBSP;RECVSIZEBUF&NBSP;=&NBSP;SOCK.RECV (bufSize) f.write (BUF) Recvsize += len (buf ) Filesizetotal += recvsizecnt += 1print (' Cnt: %d, time cost: %.2fs,  %s '%  (Cnt, time.time ()-starttime, pathfile)) Sock.close () sOckserver.close () print (' Cnt: %d, time total: %.2fs, send bytes:%ld b '%   (Cnt, time.time ()-starttime, filesizetotal)) if __name__ ==  ' __main__ ':P rocall () Print (' Time total:%.2fs '  %  (Time.time ()  - starttime))


"Client.py"

#encoding: utf-8#author: walker#date: 2017-12-01  #summary:  with socket connection tcp  Server to transfer files import os, timeimport socketimport structcur_dir_fullpath =  Os.path.dirname (Os.path.abspath (__file__)) host =  ' 127.0.0.1 ' port = 6789bufsize =  8196FmtHead =  ' 256sHL ' #L决定单个文件必须小于4GSrcRoot  = os.path.join (cur_dir_fullpath,  ' Input ') #源目录ExtSet  = {'. pdf ',  '. html ',  '. htm '} #后缀列表StartTime  = time.time () # Start Time Def procall (): Cnt = 0filesizetotal = 0sockclient = socket.socket (socket . Af_inet, socket. SOCK_STREAM) print (' connect %s:%d  ... '  %  (host, port)) Sockclient.connect ((host,  Port) print (' local: %s:%d '  %  (Sockclient.getsockname ())) for parent, dirnames,  Filenames in os.walk (srcroot): For filename in filenames:if os.path.splitext ( filename) [1].lower () &nbsP;not in extset: #排除非指定后缀的文件continuepathfile  = os.path.join (parent, filename) RelPath  = pathfile[len (srcroot):].strip (OS.PATH.SEP) #相对路径 (relative to Srcroot) filesize = os.path.getsize ( Pathfile) #发送数据包头 (relative path, relative path length, file size) pkghead = struct.pack (Fmthead, relpath.encode (' UTF8 '),  Len (RelPath),  filesize) Sockclient.sendall (pkghead) with open (pathfile, mode= ' RB ')  as f : While true:buf = f.read (BufSize) If len (BUF)  < 1:breaksockclient.sendall (BUF) Filesizetotal += filesizecnt += 1print (' Cnt: %d, time cost: %.2fs,  %s '%  (Cnt, time.time ()-starttime, pathfile)) #发送文件传送结束消息pkgHead  = struct.pack ( fmthead,  ' over ' encode (' UTF8 '),  len (' over '),  0) Sockclient.sendall (pkghead) sockclient.close () Print (' Cnt: %d, time total: %.2fs, send bytes:%ld b '%  (cnt,  Time.time ()-starttime, filesizetotal)) if __name__ ==  ' __main__ ':             procall ()         print (' Time total:%.2fs '   %  (Time.time ()  - starttime))


"Related reading"

1. struct

2. Socket

3, Socket programming HOWTO


Walker's Journal * * *


Python TCP Socket Transfer file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.