通过Socket Python发送多个文件和控制消息

时间:2019-01-15 18:36:39

标签: python python-3.x sockets networking

我正在尝试使用客户端和服务器python脚本在python中创建一个应用程序,以将目标目录与备份目录同步。

我已经能够让客户端将单个文件发送到服务器,并使其正确写入。但是,我还需要发送一条控制消息,指示服务器需要处理文件(添加,删除或修改文件)。我在通过“控制消息”一次添加多个文件时遇到问题。

一次发送多个文件时,服务器会正​​确获取客户端发送给它的所有数据,但是它将所有这些都写入一个文件,包括后续的“控制消息”。我试图让服务器识别客户端到达文件末尾时发送的空白字符串,但这似乎不起作用。

这是我的代码:

Client.py

import socket
import keyboard
import os
import time

class Client:

    def __init__(self, port):

        self.port = port
        self.s = socket.socket()

    def setDirectory(self):

        print("Please enter the filepath to the directory you want to track")
        self.dir = input()
        print("%s is now being tracked" % self.dir)
        self.old = dict ([(f, None) for f in os.listdir (self.dir)])

    def socketCleanup(self):    

        self.s.shutdown(socket.SHUT_RDWR)
        self.s.close()    

    def sendChanges(self, added, removed):    

        self.s.connect(('127.0.0.1', self.port))
        print("Connected")    

        if len(added) > 0:
            for filename in added:

                self.s.send("add".encode())
                f = open((self.dir + filename),'rb')
                l = f.read(1)    

                while (l):
                    print("Sending...")
                    print(l.decode("utf-8"))
                    self.s.send(l)
                    l = f.read(1)    

                f.close()    

                print("Done Sending")    

        if len(removed) > 0:    

            pass    

        self.socketCleanup()            

    def monitor(self):

        self.new = dict ([(f, None) for f in os.listdir (self.dir)])
        self.added = [f for f in self.new if not f in self.old]
        self.removed = [f for f in self.old if not f in self.new]    

        for filenames in self.added:
            print(filenames)    

        if (len(self.added) + len(self.removed)) > 0 :
            self.sendChanges(self.added, self.removed)
        else:
            print("No Changes")    

        self.added.clear()
        self.removed.clear()
        self.old = self.new    

fileClient = Client(1234)
fileClient.setDirectory()    

while 1:    

    time.sleep (10)    

    try: 
        if keyboard.is_pressed('d'):
            os.system('clear')
            dropboxClient.setDirectory()
        if keyboard.is_pressed('c'):
            break
    except:
        print("The d key needs to be pressed in order to change the directory")    

    fileClient.monitor()    

fileClient.socketCleanup()

Server.py

import socket                    

class Server:    

    backupdir = path_to_backup_directory
    nextname = "file"
    number = 1    

    def __init__(self, port):
        self.port = port
        self.s = socket.socket()
        self.connect()    

    def connect(self):
        self.s.bind(('', self.port))
        self.s.listen(1)
        print("socket is listening")
        self.c, self.addr = self.s.accept()    

    def closeConnection(self):
        st='Sync Complete'
        byt=st.encode()
        self.c.send(byt)    

    def addFile(self):    

        f = open((self.backupdir + self.nextname), 'w+')
        l = self.c.recv(1)
        while (l.decode("utf-8")):
            print("Receiving...")
            f.write(l.decode("utf-8"))
            print(l.decode("utf-8"))
            l = self.c.recv(1)    

        f.close()
        self.nextname = "file" + str(self.number)
        print("here")
        self.number += 1    

    def deleteFile():
        pass    

    def rewriteFile():
        pass    

fileServer = Server(1234)    

while 1:  

    command = fileServer.c.recv(3).decode("utf-8")    

    if command == "add":
        fileServer.addFile()
    elif command == "del":
        fileServer.deleteFile()
    elif command == "rwr":
        fileServer.rewriteFile()
    else:
        pass

此外,我对python还是很陌生,所以我不确定是否要以正确的方式进行操作。任何建议将不胜感激。

0 个答案:

没有答案