python3通过socket发送文件

时间:2018-02-15 17:17:14

标签: python-3.x sockets

一切都应该没问题, 但收到的文件总是被损坏 数据匹配没有任何区别 删除哈希标记 来自print(数据),如果你想看到二进制和自己编译 .................................................. .................. .................................................. ..................

server.py

import socket, threading, os
from time import sleep


host, port = '127.0.0.1', 442


class transfer :
    mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    mysocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    def __init__(self):
        self.mysocket.bind((host, port))
        print(' Server is ready ..')
        self.mysocket.listen(5)
        conn, addr = self.mysocket.accept()

        file_name = 'test.webm'
        size = os.path.getsize(file_name)
        print(' file size : {}'.format(str(size)))

        send_thread = threading.Thread(target = self.send_file, args=(file_name, size, conn, addr, ))
        send_thread.start()

    def send_file(self, file_name, size, conn, addr):
        with open(file_name, 'rb') as file:
            data = file.read(1024)
            conn.send(data)
            while data != bytes(''.encode()):
                #print(data)
                data = file.read(1024)
                conn.send(data)

            print(' File sent successfully.')


Transfer = transfer()

client.py

import socket, sys, threading

from time import sleep

host, port = '127.0.0.1', 442


class recv_data :
    mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    mysocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    mysocket.connect((host, port))

    def __init__(self):
        data = self.mysocket.recv(1024)
        f = open('newfile.webm', 'wb')
        while data != bytes(''.encode()):
            #print(data)
            data = self.mysocket.recv(1024)
            f.write(data)


re = recv_data()

1 个答案:

答案 0 :(得分:2)

在这里的客户:

def __init__(self):
    data = self.mysocket.recv(1024)
    f = open('newfile.webm', 'wb')
    while data != bytes(''.encode()):
        #print(data)
        data = self.mysocket.recv(1024)
        f.write(data)

程序永远不会将第一个recv的结果写入文件。该数据被丢弃并被第二个recv的结果取代,后者成为写入文件的第一个数据。

要解决此问题,请将f.write移到第二个recv来电之上。