如何将文件从服务器发送回客户端?

时间:2021-02-15 05:54:05

标签: python python-3.x sockets socket.io

我必须实现一个客户端-服务器应用程序,其中客户端必须发送一个带有数据的文本文件。服务器必须接收文件,纠正拼写错误的单词,然后将文件返回给客户端。

我现在可以成功地将文件从客户端发送到服务器,并且可以更正拼写。现在,我不确定如何将文件从服务器发送回客户端。

这是我当前的代码:

客户:

def readFile(self):
        global f
        filename = filedialog.askopenfilename(filetypes = [('txt', '*txt')])

        # filename = filedialog.askopenfilename(initialdir= "C://Users//Desktop//assignments//spellcheck-master")

        fileHandle = open(filename, 'r')
        for i, line in enumerate(fileHandle.readlines()):
            # import pdb;pdb.set_trace()
            message = (f"{self.name}: {line}") 
            client.send(message.encode(FORMAT))  

        fileHandle.close()

服务器:

def handle(self, conn, addr):
            # receive the file infos
        # receive using client socket, not server socket
        # import pdb; pdb.set_trace()
        received = conn.recv(BUFFER_SIZE).decode(FORMAT)
        filename, filesize = received.split(SEPARATOR)
        # remove absolute path if there is
        filename = "/Users/Desktop/Distributed_System/spellcheck/convertextTxt.txt"
        # convert to integer
        filesize = int(filesize)
        
        # start receiving the file from the socket
        # and writing to the file stream
        f = open(filename, 'w')
        while True:
            # read 1024 bytes from the socket (receive)
            bytes_read = conn.recv(BUFFER_SIZE)
            if not bytes_read:
                print("Nothing received")
                # nothing is received
                # file transmitting is done
                break
            # write to the file the bytes we just received
            rtf = bytes_read.decode(FORMAT)
            text = rtf_to_text(rtf)
            convertedTxt = self.spellCheck(text) 
            f.write(convertedTxt)
            f.close()

现在,如何将转换后的文件从服务器发送回客户端?

0 个答案:

没有答案