Python tcp socket転送ファイル
【試験環境】
【server.py】
os:Windows 10 x64
Python:3.6.3
【server.py】
#encoding: utf-8
#author: walker
#date: 2017-12-01
#summary: socket tcp server
import os, time
import socket
import struct
cur_dir_fullpath = os.path.dirname(os.path.abspath(__file__))
Host = '127.0.0.1'
Port = 6789
BufSize = 8196
FmtHead = '256sHL' #L 4G
FmtHeadLen = struct.calcsize(FmtHead)
DstRoot = os.path.join(cur_dir_fullpath, 'output') #
StartTime = time.time() #
def ProcAll():
cnt = 0
fileSizeTotal = 0
sockServer = 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:
# ( , , )
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!')
break
pathfile = 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 #
while True:
if recvSize >= fileSize:
break
bufSize = BufSize
if fileSize - recvSize
【client.py】
#encoding: utf-8
#author: walker
#date: 2017-12-01
#summary: socket tcp server
import os, time
import socket
import struct
cur_dir_fullpath = os.path.dirname(os.path.abspath(__file__))
Host = '127.0.0.1'
Port = 6789
BufSize = 8196
FmtHead = '256sHL' #L 4G
SrcRoot = os.path.join(cur_dir_fullpath, 'input') #
ExtSet = {'.pdf', '.html', '.htm'} #
StartTime = time.time() #
def ProcAll():
cnt = 0
fileSizeTotal = 0
sockClient = 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() not in ExtSet: #
continue
pathfile = os.path.join(parent, filename)
relPath = pathfile[len(SrcRoot):].strip(os.path.sep) # ( SrcRoot)
fileSize = os.path.getsize(pathfile)
# ( , , )
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、struct
2、socket
3、Socket Programming HOWTO
*** walker ***