py文件传输

本文参考:http://blog.163.com/kongdelu2009@yeah/blog/static/1119952072009102562126194/

发送端程序:

# -*- coding: utf8 -*-

import struct

import logging.handlers  

import sys;

from socket import *

import os;

import string;

LOG_FILE = 'send.log'

//通过log模块将日志输出到文件当中

handler = logging.handlers.RotatingFileHandler(LOG_FILE,mode = 'w', maxBytes = 1024*1024, backupCount = 5) # 实例化handler   

fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(message)s'  

formatter = logging.Formatter(fmt)   # 实例化formatter  

handler.setFormatter(formatter)      # 为handler添加formatter  

logger = logging.getLogger('Send.log')    # 获取名为tst的logger  

logger.addHandler(handler)           # 为logger添加handler  

logger.setLevel(logging.DEBUG)  

//增加handle,将日志输出到控制台

console = logging.StreamHandler()  

console.setLevel(logging.DEBUG)  

# 设置日志打印格式  

console.setFormatter(formatter)  

logger.addHandler(console)

//命令行参数处理

iArgLen = len(sys.argv);

if iArgLen < 4:

    logger.debug('command arg is not enough')

    sys.exit(0);

#网络地址

addrString = sys.argv[1];

logger.debug('addrString = ' + addrString);

#必须使用fullPath

filename = sys.argv[2];

logger.debug('filename = ' + filename);

path,fName=os.path.split(filename);  

#文件传输过去的存储地址

# ServerSaveAddr = sys.argv[3];

# ServerSaveAddr = "%s\\%s"%(ServerSaveAddr,fName);

# logger.debug('ServerSaveAddr = %s'%(ServerSaveAddr));

#版本号

version = sys.argv[3];

logger.debug('version = %s'%(version));

#map类型  0-DB 1- OB

iType = int(sys.argv[4]);

logger.debug('iType = %d'%(iType));

ADDR = (addrString,5454);

BUFSIZE = 1024

FILEINFO_SIZE=struct.calcsize('128s11I')

logger.debug('fineinfo_size = %d'%(FILEINFO_SIZE));

sendSock = socket(AF_INET,SOCK_STREAM)

#try:

sendSock.connect(ADDR)

version = version.encode('utf-8');

iLen = len(version);

logger.debug('versin string Len = %d'%(iLen));

//序列号相关信息至内存

fhead=struct.pack('128s11I',version,iType,iLen,0,0,0,0,0,0,os.stat(filename).st_size,0,0)

logger.debug("fheadsize %d" %(len(fhead)));

logger.debug("filesize %d" %(os.stat(filename).st_size));

ret = sendSock.send(fhead)

logger.debug('head send success ,size = %d'%(ret));

fp = open(filename,'rb')

while 1:

    filedata = fp.read(BUFSIZE)

    if not filedata: break

    ret = sendSock.send(filedata);

    #logger.debug('file send  ,size = %d'%(ret));

    

logger.debug('file send success');

fp.close();

sendSock.close();

##except:

#    print('An exception happened ,clear and exit');

#    if  'fp' in locals().keys() :

#        fp.close();

#sendSock.close();

logger.debug('Aplication End');

//接受端程序

# -*- coding: utf8 -*-

from socket import *

import os

import struct

import sys

import time;

import logging  

import logging.handlers  

 

LOG_FILE = 'Recv.log'  

handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes = 1024*1024, backupCount = 5) # ʵ��handler   

fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(message)s'  

  

formatter = logging.Formatter(fmt)   # ʵ��formatter  

handler.setFormatter(formatter)      # Ϊhandler���formatter  

  

logger = logging.getLogger('Recv.log')    # ��ȡ��Ϊtst��logger  

logger.addHandler(handler)           # Ϊlogger���handler  

logger.setLevel(logging.DEBUG)  

console = logging.StreamHandler()  

console.setLevel(logging.DEBUG)  

console.setFormatter(formatter)  

logger.addHandler(console)

iArgLen = len(sys.argv);

if iArgLen < 2:

    logger.debug('command arg is not enough')

    sys.exit(0);

addrString = sys.argv[1];

logger.debug('addrString = ' + addrString);

ADDR = ('',5454);

logger.debug(ADDR);

BUFSIZE = 1024

FILEINFO_SIZE=struct.calcsize('128s11I')

logger.debug('fineinfo_size = %d'%(FILEINFO_SIZE));

recvSock = socket(AF_INET,SOCK_STREAM)

recvSock.bind(ADDR)

recvSock.listen(True)

logger.debug("wait for connect\r\n");

bTimeOut = False;

fileSize = 0;

//接受相关数据,需要进行超时处理

while 1:

    conn,addr = recvSock.accept()

    logger.debug("-------------------connect success------------------- ");

    fhead = conn.recv(FILEINFO_SIZE)
    fEnterClock = time.clock();

    bTimeOut = False;

    while 1:

        iLen = len(fhead);

        if iLen != 0:

            if iLen != FILEINFO_SIZE:

                logging.debug('The Recive headLen(%d) is not fit(%d)'%(iLen,FILEINFO_SIZE))

                sys.exit(0);  

        else:

            if time.clock() - fEnterClock > 3:

                bTimeOut = True;

                break;

            continue;

        logger.debug('fheadsize = %d'%(len(fhead)));

        version,iType,iLen,temp3,temp4,temp5,temp6,temp7,temp8,fileSize,temp10,temp11=struct.unpack('128s11I',fhead)

        logger.debug('fliesize %d'%(fileSize));

        break;

    if bTimeOut == True:

        logger.debug('This Connect TimeOut');

        conn.close();

        continue;

    logger.debug("file head receive success ");

    

    version = version.decode('utf-8');

    version = version[0:iLen];

    logger.debug("version   = %s "%(version));

    

    filename = '%s.1zip'%(version);

    

    logger.debug("filename = %s"%(filename));

    

    filename = filename.strip('\00') #...

    

    fp = open(filename,'wb')

    

    restsize = fileSize

    

    logger.debug("begin receice file, filesize = %d"%(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

    

    logger.debug('file receive success');

    

    fp.close()

    conn.close()

    

    # save the version number

    fVersion = open('version.txt','w');

    fVersion.write(version);

    fVersion.close();

    logger.debug('save version success');

    # save the position number

    fPos = open('CopyPostion.txt','w');

    strType = ('%d'%(iType));

    fPos.write(strType);

    fPos.close();

    logger.debug('save copyPostion success');

    # open the copy bat command

    os.system('test.bat');

    

recvSock.close()

logger.debug('socket close');

总结:

1、try/except/finally;

2、 if  'fp' in locals().keys() : 判断本地变量是否存在

3、dic = dic(), list = [], str()

上一篇:IOS SWIFT基本画图教程


下一篇:C# ~ 从 XML 到 Linq 到 Linq to XML