Python sockets连续jpg文件共享

问题描述

我在一台客户端和一台服务器上使用 Python 套接字。我正在为客户端编写一个程序,以不断将压缩的 jpg 文件发送到服务器。目前我只能发送第一个压缩文件。之后,程序就坐下来了。我相信这可能与我的服务器逻辑有关,但我不确定问题出在哪里。理想情况下,我希望客户端不断发送文件,直到我停止该程序。请帮忙!

服务器:

import socket
import tqdm
import os

# device's IP Address (0.0.0.0 ensures the host will be reachable on all of its IP Addresses)
SERVER_HOST = '0.0.0.0'
SERVER_PORT = 5555

# receive 500000 bytes each time
BUFFER_SIZE = 500000
SEParaTOR = '<SEParaTOR>'

# create the server socket
# TCP socket
serverSocket = socket.socket()

# bind the socket to our local address
serverSocket.bind((SERVER_HOST,SERVER_PORT))
#serverSocket.setsockopt(socket.soL_SOCKET,socket.so_REUSEADDR,1)


# enabling our server to accept connections
# 5 here is the number of unaccepted connections the system will allow before refusing new connections
serverSocket.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")



try:
    while True:
        # accept connection if there is any
        client_socket,address = serverSocket.accept()
        # if below code is executed,that means the sender is connected
        print(f"[+] {address} is connected.")
        
        # receive the file info (name and size)
        # receive using client socket,not server socket
        received = client_socket.recv(BUFFER_SIZE).decode()
        filename,filesize = received.split(SEParaTOR)

        # remove absolute path if there is one
        #filename = os.path.basename(filename)

        # convert to integer
        filesize = int(filesize)

        #start receiving the file from the socket and writing to the file stream
        progress = tqdm.tqdm(range(filesize),f"Receiving {filename}",unit="B",unit_scale=True,unit_divisor=1024)

        with open(filename,"wb") as f:
            while True:
                # read 1024 bytes from the socket (receive)
                bytes_read = client_socket.recv(BUFFER_SIZE)
                if not bytes_read:
                    # nothing is received
                    # file transmitting is done
                    break
                # write to the file the bytes just received
                f.write(bytes_read)
                # update the progess bar
                progress.update(len(bytes_read))
        serverSocket.send(b'Picture was received').encode()
except IOError as e:
    pass
finally:
    # close the client socket
    client_socket.close()

    # close the server socket
    serverSocket.close()

客户:

import time
import picamera

#for socket connection and sending files
import socket
from tqdm import tqdm
import os

# for file compression
import tarfile

# for creating multiple threads
import threading


SEParaTOR = '<SEParaTOR>'

# Send 500000 bytes each time
BUFFER_SIZE = 500000
#server IP Address
host = 'put your server IP Address here'
port = 5555

# Create the client socket
clientSocket = socket.socket()
print(f"[+] Connecting to {host}:{port}")

clientSocket.connect((host,port))
print(f"[+] Connected.")

def compress(tar_file,members):
    '''
    Adds files ('members') to a tar_file and compress it
    '''
    # open file for gzip compressed writing
    tar = tarfile.open(tar_file,mode='w:gz')
    # with progress bar
    # set the progress bar
    progress = tqdm(members)
    for member in progress:
        # add file/folder/link to the tar file (compress)
        tar.add(member)
        # set the progress description of the progress bar
        progress.set_description(f'Compressing {member}')
    # close the file
    tar.close()

def cameraLocalSave(filename):
    with picamera.PiCamera() as camera:
        camera.resolution = (1024,768)
        camera.start_preview()
        # Camera warm-up time
        time.sleep(2)
        # tells the camera where to store the file and the file name
        camera.capture(filename)

def sendCompressedFile(comp_filename,comp_filesize):
    # encode() function encodes the string to 'utf-8' for sending to server
    clientSocket.send(f"{comp_filename}{SEParaTOR}{comp_filesize}".encode())
    progress = tqdm(range(comp_filesize),f"Sending {comp_filename}",unit_divisor=1024)
    time.sleep(5)
    with open(comp_filename,"rb") as f:
        while True:
            # read the bytes from the file
            bytes_read = f.read(BUFFER_SIZE)
            if not bytes_read:
                # file transmitting is done
                break
            # we use sendall to assure transmission in busy networks
            clientSocket.sendall(bytes_read)
            # update the progress bar
            progress.update(len(bytes_read))
            
def runcamera(i):
    filename = '/home/pi/roverPhotos/RoverImage' + str(i) + '.jpg'
    cameraLocalSave(filename)
    # get the file size 
    filesize = os.path.getsize(filename)
    print('original file size: ' + str(filesize))
        
    comp_filename = '/home/pi/CompressedFiles/compressed' + str(i) + '.tar.gz'
    # compress the file
    compress(comp_filename,[filename])
        
    comp_filesize = os.path.getsize(comp_filename)
    print('compressed file size: ' + str(comp_filesize))
        
    sendCompressedFile(comp_filename,comp_filesize)
    time.sleep(5)
    #clientSocket.close()
    break
    #time.sleep(1)

def runProgram():
    i=0 # for testing sending more than one file (will use date/time later)
    while True:
    # start camera program
        runcamera(i)
        time.sleep(1)
        i+=1
        msg = clientSocket.recv(1024).decode()
        print('Server sent: ',msg)
runProgram()
# close the socket
clientSocket.close()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)