Send image to server over sockets

Asked by At

I'm trying to send image to setver, but something goes wrong. I cannot open the recived file.

Server:

    with open("image.jpg", "wb") as fw:
        print("Receiving..")
        while True:
            data = c.recv(1024)
            image += data
            if data == b'BEGIN':
                continue
            elif data == b'ENDED':
                break
            else:
                fw.write(image)
        fw.close()
        print("Received..")

Client:

    with open('/home/pi/Desktop/image_to_send.jpg', 'rb') as fs: 
       self.soc.send(b'BEGIN')
       while True:
            data = fs.read(1024)
            self.soc.send(data)
            if not data:
                break
            self.soc.send(b'ENDED')
            fs.close()

1 Answers

1
furas On Best Solutions

First mistake: you add BEGIN and ENDED to image and you save it. Besides if you will add data to imag and write it in every loop then you will save the same part of image in file many times.

with open("image.jpg", "wb") as fw:
    print("Receiving..")
    while True:
        data = c.recv(1024)
        if data == b'BEGIN':
            continue
        elif data == b'ENDED':
            break
        else:
            fw.write(data)
    fw.close()
    print("Received..")

Second mistake: you have wrong indentions in client and you run send('ENDED') after first send(data)

with open('/home/pi/Desktop/image_to_send.jpg', 'rb') as fs: 
   self.soc.send(b'BEGIN')
   while True:
        data = fs.read(1024)
        self.soc.send(data)
        if not data:
            break
   self.soc.send(b'ENDED')
   fs.close()

I would send it without BEGIN and ENDED. When client closes connection then server should receive zero data or EOF - so you could check if not data: in server and close file.