Z
Z
Zero None2021-10-07 20:57:59
Python
Zero None, 2021-10-07 20:57:59

How to send an image using socket?

Evenings. So, I took an interest in sockets in python. Wanted to send a picture.
Looked at the code on the Internet - does not fit. I tried to write myself based on what I had already seen.
server

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("", 9999))
data, addr = sock.recvfrom(1024)
print(data.decode(), addr)
with open("mi.png", "rb") as mifile:
    midata = mifile.read(1024)
    while midata:
        sock.sendto(midata, addr)
        midata = mifile.read(1024)
print("Done.")
sock.close()


client
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(("localhost", 9999))
sock.send("Hello, Server!".encode())
with open("mi2.png", "ab") as mifile:
    data = sock.recv(1024)
    while data:
        mifile.write(data)
        data = sock.recv(1024)
print("Done.")
sock.close()


The first message is sent from the client side, the server shuts down, but no data is written. My first solution was:
server
with open("mi.png", "rb") as mifile:
    midata = mifile.read()
    while midata:
        sock.sendto(midata, addr)


client
with open("mi2.png", "wb") as mifile:
    mifile.write(sock.recv(1024))


In this case, the file was saved, but was damaged (The weight of the original file was saved, but the disk space was taken up by 0 ) . In the second case, nothing is recorded at all (0 what is there, what is there.) .

How can you decide?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-10-08
@Vindicar

Well, for starters, learn the difference between TCP (SOCK_STREAM) and UDP (SOCK_DGRAM).
In the latter case, you DO NOT GUARANTEE either the fact of delivery of messages, or their correct order, and there are restrictions on the size of the message. Also the server has no idea when the client has finished sending messages.
So it's better to figure out how to establish (and correctly close!) a TCP connection and rewrite the script for it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question