Python用于局域网传输文件和对话的程序

/ 0评 / 0

想当天,我写的第一个Python的程序,语言混乱,变量乱用,根本不懂OOP,所有都是乱的,今天把这个源代码贴出来,供大家吐槽,顺便遍说一下,要是有谁想和我一起学Python的,甚至愿意和我见面的(仅限女生)都可以给我发邮件,联系方式底下有,哈哈!

要是有人想接着写这个程序,我可以重操旧业,和你一起学,顺便把它的GUI也做出来(这是我的第一个Python程序,大神勿吐槽!)

这是server端:

#!/usr/bin/python
#coding:utf-8
#FileName:局域网传输软件server.exe
_version_ = "1.0"
import re
import time
import os
import socket
import struct
import sys
cname = socket.getfqdn(socket.gethostname())
cip = socket.gethostbyname(cname)
print("您的计算机名为:",cname)
print("您的计算机ip地址为:",cip)
wenben = ['txt','jsp','crt','asp','php','py','htaccess','md5','psw']
for times in range(1,2):
    if cip == "127.0.0.1":
        print("您的计算机没有连接网络··即将退出")
        time.sleep(0.9)
        break
    while True:
        #下面是关于IP的获取和检查
        print ("\n您最好知道对方的IP地址,因为计算机名的解析失败率较高!\n")
        UI = input("请输入您的所要传输的IP地址或者计算机名: ")
        if len(UI) == 0:
            break
        if UI == '127.0.0.1':
            print ("您不能向本机传输文件!")
            continue
        patten = re.compile(r"(?< ![0-9.])((2[0-4][0-9]|25[0-5]|[01]?[0-9]{1,2})\.){3}(2[0-4][0-9]|25[0-5]|[01]?[0-9]{1,2})(?![0-9.])")
        check = patten.match(UI)
        if check:
            back=os.system('ping -n 2 -w 1 %s' % UI)
            print ("正在测试IP可联通性····")
            if back:
                print ("请检查您的IP地址是否可用!")
                continue
            else:
                print ("""
                       ***你输入的IP地址可联通!***""")
        else:
            try:
                newip = socket.gethostbyname(UI)
            except(socket.gaierror):
                print ("您所输入的计算机名无法解析,请重试")
                continue
            else:
                print ("您所输入的计算机名对应的IP为: %s 下面测试连通性···" % newip)
                back1=os.system('ping -n 2 -w 1 %s' % newip)
            if back1:
               print ("请检查您的IP地址是否可用!")
               continue
            else:
               print ("""
                      ***你输入的IP地址可联通!***""")
               UI = newip
        #下面开始进入链接部分
        port = 18702
        print ("您即将要使用对方的 %s 端口!" % port)
        while True:
            file = input("""
                    ***您可以按空格键重新选择输入ip***
请输入你的文件路径(或者对话):""")
            if len(file) == 0:
                break
            checkinput = re.compile(r'(^[A-Z]{1}[:]{1}[\\]{1})',re.I)
            checkinput1 = checkinput.match(file)
            if checkinput1:
                #########################
                checklujin = os.path.isdir(file)
                if checklujin == True:
                    youxi = file.split('\\')[-1]
                    if len(youxi) == 0:
                        print ("不能传输根目录! 请重试!")
                        continue
                    else:
                        alllist = []
                        dirlist = []
                        filelist = []
                        print("\n您输入的为路径!将会传输路径下的所有文件!\n")
                        def fun(file):
                            for files in os.listdir(file):
                                fullfiles = os.path.join(file,files)
                                alllist.append(fullfiles)
                                if os.path.isdir(fullfiles):
                                    fun(fullfiles)
                        fun(file)
                        for filetemp in alllist:
                            tempcheckdir = os.path.isdir(filetemp)
                            if tempcheckdir == True:
                                dirlist.append(filetemp)
                            else:
                                filelist.append(filetemp)
                        for i in filelist:
                            filesize = os.path.getsize(i)
                            houzhui = i.split('.')[-1]
                            if houzhui in wenben:
                                try:
                                    fileopen = os.open(i, os.O_RDONLY |os.O_BINARY)
                                    fileallon = os.read(fileopen,filesize)
                                    fileall = fileallon
                                except:
                                    print ("文件无法获取,请重试!")
                                    break
                                finally:
                                    os.close(fileopen)
                                filetype = '文本'
                            else:
                                try:
                                    fileopen = open(i,'rb',buffering=filesize)
                                    fileall = fileopen.read()
                                except:
                                    print ("无法获取文件,请重试!")
                                    continue
                                finally:
                                    fileopen.close()
                                filetype = '二进制'
                            ADDR = (UI,port)
                            sendSock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                            try:
                                sendSock.connect(ADDR)
                            except(socket.gaierror):
                                print ("您的链接无法建立,请重试!或者按回车键重新输入IP地址!")
                                break
                            except(ConnectionRefusedError):
                                print ("对方计算机主动拒绝连接,请重试!或者按回车键重新输入IP地址!")
                                break
                            except(TimeoutError):
                                print ("连接超时,请重试!")
                                break
                            except (OSError):
                                print ("您的连接请求发生对冲,请重试!")
                                break
                            zonecheck = 15991
                            filezonepack = struct.pack('i',zonecheck)
                            sendSock.send(filezonepack)
                            dirnamewithoutfirst = file.split('\\')[-1]
                            sendSock.send(dirnamewithoutfirst.encode('utf-8'))
                            time.sleep(0.1)
                            #共有,私有
                            filedirNo = len(dirlist)
                            sendSock.send(struct.pack('i',filedirNo))
                            for dirname in dirlist:
                                dirname = dirname.encode('utf-8')
                                sendSock.send(dirname)
                            sendSock.send(filetype.encode('utf-8'))
                            time.sleep(0.1)
                            filesizepack = struct.pack('i',filesize)
                            sendSock.send(filesizepack)
                            time.sleep(0.1)
                            i = i.split('\\')[-1]
                            nameoffile = i.encode('utf-8')
                            sendSock.send(nameoffile)
                            time.sleep(0.1)
                            try:
                                sendSock.send(fileall)
                            except:
                                print("文件不能传输,请重试!")
                                continue
                            time.sleep(1.0)
                            continue
                    continue
                ############################
                else:
                    checkfile = os.path.isfile(file)
                    if checkfile == False:
                        print ("您所输入的文件不存在!请重试!")
                        continue
                    else:
                        tt = file.split('\\')
                        name = tt[len(tt)-1]
                        filesize = os.path.getsize(file)
                        houzhui = name.split('.')[-1]
                        #常见的文本文件后缀
                        if houzhui in wenben:
                            try:
                                fileopen = os.open(file, os.O_RDONLY |os.O_BINARY)
                                fileallon = os.read(fileopen,filesize)
                            #fileall = fileallon.encode('utf-8')
                                fileall = fileallon
                            except:
                                print("文件无法获取,请重试!")
                                continue
                            finally:
                                os.close(fileopen)
                        ############
                        else:
                            try:
                                fileopen = open(file,'rb',buffering=filesize)
                                fileall = fileopen.read()
                            except:
                                print ("无法获取文件,请重试!")
                                continue
                            finally:
                                fileopen.close()
                        print ("您输入的是文件···可以传输")
                        print ("您的文件大小为 %d 字节" % filesize)
                zonecheck = 1
                #这里重复写是因为上面的变量时局部的,我不会用GOLBAL
                tt = file.split('\\')
                name = tt[len(tt)-1]
            else:
                print ("您输入的是对话···可以发送!")
                fileall = file
                zonecheck = 18702
                pass
            ADDR = (UI,port)
            sendSock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            if zonecheck == 1:
                try:
                    sendSock.connect(ADDR)
                except(socket.gaierror):
                    print ("您的链接无法建立,请重试!或者按回车键重新输入IP地址!")
                    continue
                except(ConnectionRefusedError):
                    print ("对方计算机主动拒绝连接,请重试!或者按回车键重新输入IP地址!")
                    continue
                except(TimeoutError):
                    print ("连接超时,请重试!")
                    continue
                except (OSError):
                    print ("您的连接请求发生对冲,请重试!")
                    continue
                filesizepack = struct.pack('i',filesize)
                sendSock.send(filesizepack)
                sendSock.send(name.encode('utf-8'))
                time.sleep(0.1)
                
                try:
                    sendSock.send(fileall)
                except:
                    print("文件不能传输,请重试!")
                    continue
                time.sleep(1.0)
                continue
            #对话部分
            elif zonecheck == 18702:
                try:
                    sendSock.connect(ADDR)
                    #使用BUF 18702
                    yanzheng = struct.pack('i',zonecheck)
                    duihua = fileall.encode('utf-8')
                except(socket.gaierror):
                    print ("您的链接无法建立,请重试!或者按回车键重新输入IP地址!")
                    continue
                except(ConnectionRefusedError):
                    print ("对方计算机主动拒绝连接,请重试!或者按回车键重新输入IP地址!")
                    continue
                except(TimeoutError):
                    print ("连接超时,请重试!")
                    continue
                except (OSError):
                    print ("您的连接请求发生对冲,请重试!")
                    continue
                else:
                    try:
                        sendSock.send(yanzheng)
                    except:
                        print("文件头失败!")
                    try:
                        sendSock.send(duihua)
                    except:
                        print ("对话传输失败")
                choose = input("文件传输成功!是否要断开连接?输入‘是’断开,回车继续")
                if choose == '是':
                    sendSock.close()
                    time.sleep(0.8)
                    print ("连接已关闭!")
                    break
                elif len(choose) == 0:
                    continue           
    break
print ("谢谢使用桂QQ的软件!")
time.sleep(0.9)

这是client端:

import os
import time
import socket
import re
import struct
import shutil
cname = socket.getfqdn(socket.gethostname())
cip = socket.gethostbyname(cname)
print("您的计算机名为:",cname)
print("您的计算机ip地址为:",cip)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
while True:
    port = 18702
    ADDR = (cip,port)
    if cip == "127.0.0.1":
        print("您的计算机没有连接网络··即将退出")
        break
    elif cip != "127.0.0.1":
        print ("正在本机服务器可联通性····")
        back = os.system('ping -n 2 -w 1 %s' % cip)
        if back:
            print ("请检查您的网络是否可用!")
            continue
        else:
            print ("""
                   ***你输入的网络可联通!***""")
            print ("将要打开端口并建立连接")
            s.bind((ADDR))
            s.listen(1)
            while True:
                print ("端口已经打开,等待服务器连接······")
                test,addrs = s.accept()
                print ("服务器已经连接,地址为:",addrs)
                print ("开始传输····请等待")
                bufpack = test.recv(4)
                bufin = struct.unpack('i',bufpack)
                buf = bufin[0]
                namein = test.recv(1024)
                nameunpack = namein.decode('utf-8')
                name = nameunpack
####nme 文件夹名
                wenben = ['txt','asp','jsp','crt','php','py','htaccess',
                          'md5','psw','ini']
                houzhui = name.split('.')[-1]
                fileaddr = (name)
                if buf == 18702:
                    name = namein.decode('utf-8')
                    print ("对话:",name)
                    continue

                if buf == 15991:
                    checkdir = os.path.isdir('D:\\收到的文件')
                    if checkdir == False:
                        os.mkdir('D:\\收到的文件')
                    else:
                        pass
                    checkdirrecv = os.path.isdir('D:\\收到的文件\\ %s ' % name)
                    dirname = ('D:\\收到的文件\\ %s ' % name)
                    if checkdirrecv == False:
                        os.mkdir(dirname)
                    else:
                        pass
                    filedirNo = struct.unpack('i',(test.recv(1024)))[0]
                    filedirlist = []
                    for filedir in range(0,filedirNo):
                        filedir = test.recv(1024)
                        filedir = filedir.decode('utf-8')
                        filedirlist.append(filedir)
                    for filedira in filedirlist:
                        temp = os.path.isdir(filedir)
                        if temp == True:
                            pass
                        else:
                            pass
                    checkfiletypein = test.recv(1024)
                    checkfiletype = checkfiletypein.decode('utf-8')
                    filesizein = test.recv(1024)
                    filesize = struct.unpack('i',filesizein)[-1]
                    filenamein = test.recv(1024)
                    filename = filenamein.decode('utf-8')
                    name = name.split('.')[0]
                    fileaddr = ('D:\\收到的文件' + '\\' + name)
                    print ("文件位置: ",fileaddr)
                    if checkfiletype == '二进制':
                        file = open(filename,'ab')
                        bufMB = filesize/1024/1024
                        print ("您的文件大小为 %f MB" % bufMB)
                        print ("您的文件名为:",filename)
                        while True:
                            filebufsize = os.path.getsize(filename)
                            bilvfloa = filebufsize/filesize*100
                            bilv = "%.2lf" % bilvfloa
                            if bilvfloa != 100:
                                re = test.recv(filesize)
                                print ("您的文件已经传输了:",bilv + "%",end='\r')
                            elif bilvfloa == 100:
                                os.system("cls")
                                print("传输完成!")
                                break
                            time.sleep(0.8)
                            file.write(re)
                        ####移动文件
                        file.close()
                        os.system('move %s %s' % (filename,fileaddr)) 
                    elif checkfiletype == '文本':
                        file = os.open(filename, os.O_WRONLY|os.O_CREAT|os.O_BINARY)
                        bufMB = filesize/1024/1024
                        print ("您的文件大小为 %f MB" % bufMB)
                        print ("您的文件名为:",filename)
                        while True:
                            filebufsize = os.path.getsize(filename)
                            bilvfloa = filebufsize/filesize*100
                            bilv = "%.2lf" % bilvfloa
                            if bilvfloa != 100:
                                re = test.recv(filesize)
                                print ("您的文件已经传输了:",bilv + "%",end='\r')
                            elif bilvfloa == 100:
                                os.system("cls")
                                print("传输完成!")
                                break
                            time.sleep(0.8)
                            os.write(file,re)
                        os.close(file)
                        os.system('move %s %s' % (filename,fileaddr))
                    print ("您收到的目录将会在 D:/收到的文件 目录下!")
                else:
                    if houzhui in wenben:
                        file = os.open(fileaddr, os.O_WRONLY|os.O_CREAT|os.O_BINARY)
                        bufMB = buf/1024/1024
                        print ("您的文件大小为 %f MB" % bufMB)
                        print ("您的文件名为:",name)
                        while True:
                            filebufsize = os.path.getsize(fileaddr)
                            bilvfloa = filebufsize/buf*100
                            bilv = "%.2lf" % bilvfloa
                            if bilvfloa != 100:
                                re = test.recv(buf)
                                #neirong = re.decode('utf-8')
                                neirong = re
                                print ("您的文件已经传输了:",bilv + "%",end='\r')
                            elif bilvfloa == 100:
                                os.system("cls")
                                print ("传输完成")
                                break
                            time.sleep(0.8)
                            os.write(file,re)
                        os.close(file)
                    else:
                        file = open(fileaddr,'ab')
                        bufMB = buf/1024/1024
                        print ("您的文件大小为 %f MB" % bufMB)
                        print ("您的文件名为:",name)
                        while True:
                            filebufsize = os.path.getsize(fileaddr)
                            bilvfloa = filebufsize/buf*100
                            bilv = "%.2lf" % bilvfloa
                            if bilvfloa != 100:
                                re = test.recv(buf)
                                print ("您的文件已经传输了:",bilv + "%",end='\r')
                            elif bilvfloa == 100:
                                os.system("cls")
                                print("传输完成!")
                                break
                            time.sleep(0.8)
                            file.write(re)
                        file.close()
print ("谢谢使用!")
time.sleep(1.0)

再说一遍,大神勿吐槽!

知识共享许可协议
本作品采用知识共享署名 4.0 国际许可协议进行许可。

发表评论

电子邮件地址不会被公开。 必填项已用*标注