sending images using python tcp socket

4.4k views Asked by At

i'm new in python and english :). i'm trying to send an image file usşng python sockets and i have written this cosdes. it says it work but i get an empty file or missing image file. this is the codes i've written:

server:

import socket


host = socket.gethostname()

port = 5000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((host, port))

s.listen(1)

sunucu , adres = s.accept()

print "baglanti saglandi"

def recvall(baglanti, buf):

    data = ""
    while len(data) < buf:

        packet = baglanti.recv(buf - len(data))

        if not packet:

            return None

        data += packet

    return data


f = open("ggg.png", "w")

while True:

    veri = sunucu.recv(512)

    if not veri:

        break

    f.write(veri)

f.close()

print "resim alindi."


sunucu.close()

s.close()

and client:

import socket


host = socket.gethostname()

port = 5000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((host , port))



f = open("ornekresim.png", "r")

while True:

    veri = f.readline(512)

    if not veri:

        break

    s.send(veri)

f.close()

print "resim gonderildi"

s.close()
1

There are 1 answers

0
Some programmer dude On

By default the Python function open opens file in text mode, meaning it will handle all input/output as text, while an image is decidedly binary.

A file in text mode will do thing like translating newline sequences (which are different on different systems). That means the data you read will be corrupted.

To open a file in binary mode, then append 'b' to the mode flags, like e.g.

f = open("ornekresim.png", "rb")  # <-- Note the 'b' in the mode

However, with your code this leads to another problem, namely that you can't use readline anymore. Not that it made much sense anyway, reading binary data as lines since there are no "lines" in binary data.

You have to use the read function instead.