Python套接字/线程将文件从服务器发送到客户端

发布于 2025-02-09 18:41:37 字数 5182 浏览 1 评论 0原文

我正在使用Python(插座/线程)进行项目,其中一部分说我需要单击一个按钮,从服务器中选择文件并将其发送给客户端(我仍然没有创建页面和按钮) 我尝试先使用CMD命令进行此操作,然后再访问网站 +按钮! 问题是,我编写了一个CMD服务器/客户端代码,该代码使我可以控制客户端CMD(好像我正在使用网站按钮进行操作),让我解释一下! 正如您在第一张图片中看到的那样,服务器可以列出活动客户端“客户端”,然后选择他想连接到“选择0”的端 server 连接后,我可以发送命令,客户执行它们,就像您在第二张图片中看到的那样 客户端 一切正常,但是我尝试添加另一个函数,当我连接到客户端后,我在键入命令“发送”时发送文件,仅在上面的图片中使用“客户端”和“ select 0”命令。 问题是,即使我在服务器CMD中键入“发送”,它也行不通,它说:“错误发送命令!”,tryy除外(execpt消息) 发送不工作 我将链接重要功能的图片,以便您尝试了解我要做的事情: 摘要:1-我想从服务器发送命令“发送”,该命令将文件发送给客户端 2-我希望客户端读取发送命令并从服务器获取文件 谢谢 ! 服务器代码: 列出所有连接的客户端并选择要连接到并发送命令/文件的客户端的功能: 客户 将命令和文件发送给客户端的功能(我不知道应该如何知道它必须发送文件的客户端) 发送命令/文件 客户端代码: 最后,获取文件和命令并执行它们的功能 executecommands/getfiles

代码

theSocket = socket.socket()
theSocket.bind((host,port))
connection,address = theSocket.accept()

#Display all the current active connections
def listConnections() :
    resultsData = ""

    #Check if a connection is still active or ont
    for isUnactive, aConnection in enumerate(connectionsList) :
        try :
            #Send string test
            aConnection.send(str.encode(" "))
            aConnection.recv(201480)

        except :
            #Delete if not active
            del connectionsList[isUnactive]
            del addressesList[isUnactive]
            continue

        resultsData = str(isUnactive) + " " + str(addressesList[isUnactive][0]) + " " + str(addressesList[isUnactive][1]) + "\n"

    print("----- Clients -----" + "\n" + resultsData)

#Choose a client target to connect to
def getTarget(cmd) :
    try :
        #Choose a client
        targetChosen = cmd.replace("Select ", "")
        targetChosen = int(targetChosen)

        #Connect to the the chosen client
        connection = connectionsList[targetChosen]
        print("You are now connected to : " + str(addressesList[targetChosen][0]))
        print(str(addressesList[targetChosen][0]) + "> ", end="")
        return connection

        '''
        Something like :
            173.249.21.59> Echo Hey
                Hey
        '''

    except :
        print("Selection not valid !")
        return listConnections()

#Send commands to the chosen client
def sendTargetCommands(connection) :
    while True :
        try :
            cmd = input()

            if cmd == "Quit" :
                break
        
            if cmd == "Send" :
                sendFile()

            #Send the command to the client
            if len(str.encode(cmd)) > 0 :
                connection.send(str.encode(cmd))
                clientResponse = str(connection.recv(1024), "utf-8")
                print(clientResponse, end="")

        except :
            print("Error sending the command !")
            break

def sendFile() :
    #Opening the file to send
    fileSending = open("Profiles.txt", 'rb')

    #Reading the file to send
    dataFile = fileSending.read()

    #Sending the file
    theSocket.send(fileSending.encode("utf-8"))

    #Sending the file data
    theSocket.send(dataFile.encode("utf-8"))

    #Closing the file
    fileSending.close()

theSocket.connect((host,port))

if theSocket :
    print("Connected to the server successfull !")

#Trying to get the files and save them
def recieveFile ():
    print("Receiving files ...")
    fileName = theSocket.recv(1024).decode("utf-8")
    print("fileName Received !")    
    fileData = open(fileName, "wb")
    print("fileData Written !")
    dataFile = theSocket.recv(1024).decode("utf-8")
    print("dataFile Received !")
    fileData.write(dataFile)
    print("dataFile Written !")
    fileData.close()
    print("fileData Closed !")

def commandsReceiving() :
    while True :
        print("Receiving commands ...")
        dataReceiver = theSocket.recv(1024)
        if dataReceiver[:2].decode("utf-8") == 'cd':
            os.chdir(dataReceiver[3:].decode("utf-8"))
        
        #If the command from the server is "Send" call the function above and try to get the files
        if dataReceiver.decode("utf-8") == "Send" :
            recieveFile()

        if len(dataReceiver) > 0 :
            cmd = subprocess.Popen(dataReceiver[:].decode("utf-8"),shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)
            outputByte = cmd.stdout.read() + cmd.stderr.read()
            outputString = str(outputByte, "utf-8")
            currentDirectory = os.getcwd() + "> "
            theSocket.send(str.encode(outputString + currentDirectory))
            
            #If you want to show what you are writing in both computers
            print(outputString)

commandsReceiving()

服务器 帮助< 3!

I'm working on a project with Python (Sockets/Threads), and a part of it say that i need to click on a button, choose a file from the server and send it to a client (I still didn't create the page and the button)
I'm trying to do it first with the cmd commands before going to the website + button !
The thing is, i wrote a cmd server/client code that allows me to control the client cmd (As if i'm doing it with a website buttons), let me explain !
As you can see in the first picture, the server can list the active clients "Clients", and choose which one he want to connect to "Select 0"
Server
Once connected i can send commands and the client execute them as you can see in the second picture
Client
Everything is working fine, but i tried to add another function that sends a file when i type the command "Send" once i'm connected to a client, just a command like "Clients" and "Select 0" in the pictures above.
The problem is, even if i type "Send" in the server cmd, it doesn't work and it says : "Error sending the command !", the tryy except (execpt message)
Send not working
I will link pictures of the important functions for you to try and understand what i am trying to do :
In Summary : 1 - I want to send a command "Send" From Server, that send a file to the client
2 - I want the client to read the send command and get the file from the server
Thanks !
Server Code :
functions that list all the clients connected and select the client we want to connect to and send commands/files :
Clients/Select
functions that send commands and files to the client (i don't know how it's to supposed to know to which client it has to send files)
send commands/files
Client Code :
Lastly, the functions that get the files and commands and execute them
executeCommands/getFiles

SERVER CODE :(AS TEXT)

theSocket = socket.socket()
theSocket.bind((host,port))
connection,address = theSocket.accept()

#Display all the current active connections
def listConnections() :
    resultsData = ""

    #Check if a connection is still active or ont
    for isUnactive, aConnection in enumerate(connectionsList) :
        try :
            #Send string test
            aConnection.send(str.encode(" "))
            aConnection.recv(201480)

        except :
            #Delete if not active
            del connectionsList[isUnactive]
            del addressesList[isUnactive]
            continue

        resultsData = str(isUnactive) + " " + str(addressesList[isUnactive][0]) + " " + str(addressesList[isUnactive][1]) + "\n"

    print("----- Clients -----" + "\n" + resultsData)

#Choose a client target to connect to
def getTarget(cmd) :
    try :
        #Choose a client
        targetChosen = cmd.replace("Select ", "")
        targetChosen = int(targetChosen)

        #Connect to the the chosen client
        connection = connectionsList[targetChosen]
        print("You are now connected to : " + str(addressesList[targetChosen][0]))
        print(str(addressesList[targetChosen][0]) + "> ", end="")
        return connection

        '''
        Something like :
            173.249.21.59> Echo Hey
                Hey
        '''

    except :
        print("Selection not valid !")
        return listConnections()

#Send commands to the chosen client
def sendTargetCommands(connection) :
    while True :
        try :
            cmd = input()

            if cmd == "Quit" :
                break
        
            if cmd == "Send" :
                sendFile()

            #Send the command to the client
            if len(str.encode(cmd)) > 0 :
                connection.send(str.encode(cmd))
                clientResponse = str(connection.recv(1024), "utf-8")
                print(clientResponse, end="")

        except :
            print("Error sending the command !")
            break

def sendFile() :
    #Opening the file to send
    fileSending = open("Profiles.txt", 'rb')

    #Reading the file to send
    dataFile = fileSending.read()

    #Sending the file
    theSocket.send(fileSending.encode("utf-8"))

    #Sending the file data
    theSocket.send(dataFile.encode("utf-8"))

    #Closing the file
    fileSending.close()

CLIENT CODE : (AS TEXT)

theSocket.connect((host,port))

if theSocket :
    print("Connected to the server successfull !")

#Trying to get the files and save them
def recieveFile ():
    print("Receiving files ...")
    fileName = theSocket.recv(1024).decode("utf-8")
    print("fileName Received !")    
    fileData = open(fileName, "wb")
    print("fileData Written !")
    dataFile = theSocket.recv(1024).decode("utf-8")
    print("dataFile Received !")
    fileData.write(dataFile)
    print("dataFile Written !")
    fileData.close()
    print("fileData Closed !")

def commandsReceiving() :
    while True :
        print("Receiving commands ...")
        dataReceiver = theSocket.recv(1024)
        if dataReceiver[:2].decode("utf-8") == 'cd':
            os.chdir(dataReceiver[3:].decode("utf-8"))
        
        #If the command from the server is "Send" call the function above and try to get the files
        if dataReceiver.decode("utf-8") == "Send" :
            recieveFile()

        if len(dataReceiver) > 0 :
            cmd = subprocess.Popen(dataReceiver[:].decode("utf-8"),shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)
            outputByte = cmd.stdout.read() + cmd.stderr.read()
            outputString = str(outputByte, "utf-8")
            currentDirectory = os.getcwd() + "> "
            theSocket.send(str.encode(outputString + currentDirectory))
            
            #If you want to show what you are writing in both computers
            print(outputString)

commandsReceiving()

Thanks for your help <3 !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文