⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 server.py

📁 客户端服务器模式的python文件传输实例
💻 PY
字号:
'''This file is part of PypMsg.PypMsg is free software: you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation, either version 3 of the License, or(at your option) any later version.PypMsg is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See theGNU General Public License for more details.You should have received a copy of the GNU General Public Licensealong with PypMsg.  If not, see <http://www.gnu.org/licenses/>.'''import confimport socket as skimport pickle as pkimport thread as thimport osclass Server:    def __init__(self):        self.msgQue = []        self.sentAttachments = []        def startServing(self):        th.start_new(self.serve, ())        def serve(self):        self.serverSocket = sk.socket(sk.AF_INET, sk.SOCK_STREAM)        self.serverSocket.bind((conf.HOST, conf.PORT))        self.serverSocket.listen(5)        print 'Server Started on %s:%s' % (conf.HOST, conf.PORT)                while True:            clientSocket, address = self.serverSocket.accept()            data = clientSocket.recv(conf.BULK_METADATA)            print 'Bytes Recieved: ', len(data)            dict = pk.loads(data)            if dict['__MODE__'] == '__EXIT__':                clientSocket.send('EXIT SUCCESS')                break            elif dict['__MODE__'] == '__MESSAGE__':                dict['Index'] = len(self.msgQue)                dict['Address'] = str(address[0])                dict['ConnectionID'] = str(address[1])                if dict['OSep'] != os.sep:                    dict['fils'] = [(i, fn.replace(dict['OSep'], os.sep)) for i, fn in dict['fils']]                    dict['dirs'] = [(i, fn.replace(dict['OSep'], os.sep)) for i, fn in dict['dirs']]                self.msgQue.append(dict)                clientSocket.send('RECIEVED')            elif dict['__MODE__'] == '__REQFILE__':                print self.sentAttachments                print address                reqFiles = [fn.replace('\\', os.sep).replace('/', os.sep) for fn in dict['fils']]                fileLists = [x['fils'] for x in self.sentAttachments if x['Address'] == address[0]]                filelist = []                for fl in fileLists:                    for i, filename in fl:                        filelist.append(filename)                                folderLists = [x['dirs'] for x in self.sentAttachments if x['Address'] == address[0]]                folderlist = []                for fl in folderLists:                    for i, foldername in fl:                        folderlist.append(foldername)                                for filename in reqFiles:                    allow = False                    for foldername in folderlist:                        if os.path.abspath(filename).startswith(os.path.abspath(foldername)):                            allow = True                    if filename in filelist or allow:                        clientSocket.send('ACCESS GRANTED\n')                        file = open(filename, 'rb')                        while True:                            bytes = file.read(conf.BULK_FILEDATA)                            if not bytes: break                            clientSocket.send(bytes)                        file.close()                    else:                        clientSocket.send('ACCESS DENIED\n')            elif dict['__MODE__'] == '__REQFOLDER__':                print 'reqFolder'                reqFolders = [fn.replace('\\', os.sep).replace('/', os.sep) for fn in dict['dirs']]                folderLists = [x['dirs'] for x in self.sentAttachments if x['Address'] == address[0]]                folderlist = []                for fl in folderLists:                    for i, foldername in fl:                        folderlist.append(foldername)                showError = True                for foldername in reqFolders:                    print foldername                    if foldername in folderlist:                        result = [res for res in os.walk(foldername)]                        for dirname, dirs, files in os.walk(foldername):                            for filename in files:                                os.path.abspath(os.path.join(dirname, filename))                        #dict = {}                        dict['__MODE__'] = 'ACCESS GRANTED'                        dict['FolderStructure'] = result                        data = pk.dumps(dict, pk.HIGHEST_PROTOCOL)                        clientSocket.send(data)                        showError = False                    else:                        print 'not sending'                        clientSocket.send(pk.dumps({'__MODE__':'ACCESS DENIED'}))                        showError = False                if showError:                    clientSocket.send(pk.dumps({'__MODE__':'UNKNOWN ERROR'}))                    print 'reqFolders:', reqFolders                    print 'folderlist:', folderlist            elif dict['__MODE__'] == '__DUMMY_SERVER_REQ__':                clientSocket.send(pk.dumps({'__MODE__':'DUMMY_CLIENT_RES'}))            elif dict['__MODE__'] == '__DEBUG_DOWNLOAD__':                file = open(dict['FileName'].replace('/', os.sep).replace('\\', os.sep).replace(':', os.sep), 'rb')                while True:                    bytes = file.read(conf.BULK_FILEDATA)                    if not bytes: break                    clientSocket.send(bytes)                file.close()            else:                clientSocket.send(pk.dumps({'__MODE__':'__MODE_ERROR__'}))                        clientSocket.close()                self.serverSocket.close()        del self.serverSocket        def downloadAttachment(self, msgIndex, attachmentName, subfile=False):        archive = [x for x in self.msgQue if x['Index'] == msgIndex][0]        downloaderSocket = sk.socket(sk.AF_INET, sk.SOCK_STREAM)        downloaderSocket.connect((archive['Address'], conf.PORT))        if attachmentName in [filenam for i, filenam in archive['fils']] or subfile:            print 'downloading file ', attachmentName            dict = {}            dict['__MODE__'] = '__REQFILE__'            dict['AuthToken'] = ''            dict['fils'] = [attachmentName]            data = pk.dumps(dict, pk.HIGHEST_PROTOCOL)            downloaderSocket.send(data)            accessStatus = downloaderSocket.makefile('r').readline()[:-1]            if accessStatus == 'ACCESS GRANTED':                recFileName = str(os.path.split(attachmentName)[1])                while os.path.exists(recFileName):                    if '.' in recFileName:                        recFileName = recFileName.replace('.', '~pf.')                    else:                        recFileName += '~pf'                recFile = open(recFileName, 'wb')                while True:                    data = downloaderSocket.recv(conf.BULK_FILEDATA)                    if not data: break                    recFile.write(data)                recFile.close()                return 'Download Successful'            else:                return 'Error Downloading file:' + accessStatus        elif attachmentName in [filenam for i, filenam in archive['dirs']]:            print 'downloading folder ', attachmentName            dict = {}            dict['__MODE__'] = '__REQFOLDER__'            dict['dirs'] = [attachmentName]            data = pk.dumps(dict, pk.HIGHEST_PROTOCOL)            downloaderSocket.send(data)            data = downloaderSocket.recv(10*conf.BULK_METADATA)            dict = pk.loads(data)            if dict['__MODE__'] == 'ACCESS GRANTED':                recFolderName = str(os.path.split(attachmentName)[1])                while os.path.exists(recFolderName):                    recFolderName = recFolderName + '~pf'                firstDirName = dict['FolderStructure'][0][0]                initialCurDir = os.path.abspath(os.curdir)                root_there = firstDirName                root_here = os.path.abspath(recFolderName)                print 'firstDirName=', firstDirName                print 'initialCurDir=', initialCurDir                print 'root_there', root_there                print 'root_here', root_here                for (dirname, dirs, files) in dict['FolderStructure']:                    dirname = dirname.replace(root_there, root_here, 1)                    if not os.path.exists(dirname):                        os.mkdir(dirname)                    #os.chdir(dirname)                    for newdir in dirs:                        os.mkdir(os.path.join(dirname, newdir))                    for newfile in files:                        print 'downloading file:', newfile                        address = archive['Address']                        req_filename = os.path.join(dirname.replace(root_here, root_there.replace(archive['OSep'], os.sep), 1), newfile)                        res_filename = os.path.join(dirname, newfile)                        sock = sk.socket(sk.AF_INET, sk.SOCK_STREAM)                        sock.connect((archive['Address'], conf.PORT))                        dict = {}                        dict['__MODE__'] = '__REQFILE__'                        dict['AuthToken'] = ''                        dict['fils'] = [req_filename]                        data = pk.dumps(dict, pk.HIGHEST_PROTOCOL)                        sock.send(data)                        accessStatus = sock.makefile('r').readline()[:-1]                        if accessStatus == 'ACCESS GRANTED':                            file = open(res_filename, 'wb')                            while True:                                data = sock.recv(conf.BULK_FILEDATA)                                if not data: break                                file.write(data)                            file.close()                            continue                        else:                            return 'Error Downloading file(' + newfile + '):' + accessStatus                        sock.close()                os.chdir(initialCurDir)                return 'Download Successful'            else:                return 'Error Downloading folder:' + dict['__MODE__']        else:            dict = {}            dict['__MODE__'] = '__DUMMY_SERVER_REQ__'            data = pk.dumps(dict, pk.HIGHEST_PROTOCOL)            downloaderSocket.send(data)            data = downloaderSocket.recv(conf.BULK_METADATA)            #dict = pk.loads(data)            #dict['__MODE__'] is supposed to be '__DUMMY_CLIENT_RES__'        downloaderSocket.close()        def stopServing(self):        exitSock = sk.socket(sk.AF_INET, sk.SOCK_STREAM)        exitSock.connect((conf.HOST, conf.PORT))        exitSock.send(pk.dumps({'__MODE__':'__EXIT__'}, pk.HIGHEST_PROTOCOL))        res = exitSock.recv(conf.BULK_METADATA)        exitSock.close()        if res == 'EXIT SUCCESS':            print 'Bye Bye!'        else:            print 'PypMsg Error: "', res, '"'

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -