如何将 JPG 文件从服务器发送到客户端

How to send a JPG file from server to client

我需要从服务器向客户端发送一个 JPG 文件。我该怎么做?

Server Code:

from PIL import ImageGrab
import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((IP, PORT))
server_socket.listen(1)
client_socket, address = server_socket.accept()
image = ImageGrab.grab()
image.save(r'screen.jpg')
# client_socket.send( ? )

当我尝试发送大量数据时它无法使用 client_socket.send(data) 所以我找到了一个解决方案:

BYTES_AMOUNT = 1024
def send_all(client_socket, data):
    while True:
        packet = bytes(data[:BYTES_AMOUNT])
        if not packet:
            break
        client_socket.send(packet)
        client_socket.recv(4)
        data = data[BYTES_AMOUNT:]


def receive_all(client_socket):
    data = bytes('')
    receiving = True
    while receiving:
        try:
            packet = client_socket.recv(BYTES_AMOUNT)
            client_socket.send('SEND')
        except Exception as error_msg:
            receiving = False
            packet = bytes('')
            print error_msg
        data += bytes(packet)
        if len(packet) < BYTES_AMOUNT:
            receiving = False
    return bytes(data)

然后:

Send:

with open('screen.jpg', 'rb') as handle:
    send_all(client_socket, handle.read())

Receive:

received_data = receive_all(client_socket)
with open('received_file.jpg', 'wb') as handle:
    handle.write(received_data)