Answer the question
In order to leave comments, you need to log in
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()
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()
with open("mi.png", "rb") as mifile:
midata = mifile.read()
while midata:
sock.sendto(midata, addr)
with open("mi2.png", "wb") as mifile:
mifile.write(sock.recv(1024))
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question