python TCP传输文件

来源:互联网 发布:apache index.html 编辑:程序博客网 时间:2024/05/29 02:37

python TCP传输文件

TCPClient.py

from socket import *import osclass sendFile():    def __init__(self,parent=None):#         super(sendFile,self).__init__(parent)                self.HOST = '192.168.7.104'        self.PORT = 6666        self.BUFSIZ = 1024        self.ADDR = (self.HOST, self.PORT)        self.tcpCliSock = socket(AF_INET, SOCK_STREAM)        self.tcpCliSock.connect(self.ADDR)    def handle(self,filename):                sendFileName = os.path.basename(filename)        file_object = open(filename,'rb')        file_size = os.path.getsize(filename)        all_the_text = file_object.read()        try:            # print "all_the_text===========",all_the_text            self.tcpCliSock.send("filename:" + sendFileName + ":" + "file_size:" + str(file_size))            if self.tcpCliSock.recv(self.BUFSIZ) == 'yes':                for i in range(file_size/self.BUFSIZ + 1):                    self.tcpCliSock.send(all_the_text[i*self.BUFSIZ:(i+1)*self.BUFSIZ])        finally:             file_object.close( )             self.tcpCliSock.close()        if __name__=="__main__":    s = sendFile()    s.handle(r'C:\file\111.txt')


TCPServer.py

from socket import *from time import ctimeimport os,timeclass TCPServer(object):    _instance = 0    def __init__(self,parent=None):        super(TCPServer, self).__init__()        self.HOST = ''        self.PORT = 6666        self.BUFSIZ = 1024        self.ADDR = (self.HOST, self.PORT)                self.tcpSerSock = socket(AF_INET, SOCK_STREAM)        self.tcpSerSock.bind(self.ADDR)        self.tcpSerSock.listen(5)        file_path = ''        file_size = 0        self.tcpCliSock, self.addr = self.tcpSerSock.accept()                    def handle(self):                while True:            data = self.tcpCliSock.recv(self.BUFSIZ)            if "filename" in data:                file_path = "C:\%s"%data.split(':')[1]                if os.path.exists(file_path):                    pass                else:                    file_object = open(file_path,'a')                self.tcpCliSock.send('%s' %('yes'))            if file_path:                                                 file_object.write( data)                file_object.close()            if not data:                break#             tcpCliSock.send('%s' %(data))        self.tcpSerSock.close()    @classmethod    def instance(cls):        if (cls._instance == 0):            cls._instance = TCPServer()                    return cls._instanceif __name__=="__main__":    server = TCPServer.instance().handle()





0 0
原创粉丝点击