首页 > 解决方案 > Python 通过套接字读取和发送文件

问题描述

我有一个服务器,它连接了 20 多个客户端。如果需要,我希望它更新这些客户端。我发现的解决方案太复杂了,或者根本不起作用,所以我认为它可能会起作用:

  1. 服务器读取“client.py”并通过套接字发送。
  2. 客户端接受数据,创建目录“更新”,将文件保存在那里并运行 bash 脚本。
  3. Bash 脚本会停止客户端,将其删除,然后将新客户端从 /update 移动到主目录。

问题是它在约 70% 的情况下有效。客户端通常在更新后工作正常。问题在于 30% 的客户端只接收文件的一部分。假设我的客户是 5kB,70% 的客户很好,30% 的客户只收到 4kB 并且 ofc 不能再运行了。

服务器:

def updateClient(self):
        try:
            file = open(str(pathlib.Path(_file_).parent.resolve())+"/client.py", "r")
            newcl = file.read()
            for host in self.active_connections:
                try:
                    host.connection.send(newcl.encode())
                except Exception as e:
                    print("[!]Error!: " + str(e))

客户:

            data = s.recv(8192)
            data = data.decode()
            newdir_path = str(pathlib.Path(_file_).parent.resolve())
            newcl_path = newdir_path+"/update/client.py"
            try:                
                os.mkdir(newdir_path+"/update")        
                print("Update directory created")
                file = open(newcl_path, 'w')
                file.write(data)
                file.close()
                print("[*] Update downloaded!")
                try:
                    process = subprocess.run("update.sh", shell=False, check=True)
                except Exception as e:
                    print(str(e))

标签: pythonsocketsnetworking

解决方案


推荐阅读