Send images using sockets Python
Question: I have some problems with this code... send not the integer image but some
bytes, is there someone than can help me? I want to send all images I find in
a folder. Thank you.

# CLIENT

    
    
    import socket
    import sys
    import os
    
    s = socket.socket()
    s.connect(("localhost",9999))       #IP address, port
    sb = 'c:\\python27\\invia'
    
    os.chdir(sb)                        #path
    
    dirs =os.listdir(sb)                #list of file
    print dirs
    
    for file in dirs:
       f=open(file, "rb")               #read image
       l = f.read()
       s.send(file)                     #send the name of the file
       st = os.stat(sb+'\\'+file).st_size  
       print str(st)
       s.send(str(st))                  #send the size of the file
       s.send(l)                        #send data of the file
       f.close()
    s.close()
    

# SERVER

    
    
    import socket
    import sys
    import os
    
    s = socket.socket()
    s.bind(("localhost",9999))
    s.listen(4)                             #number of people than can connect it
    sc, address = s.accept()
    
    print address
    sb = 'c:\\python27\\ricevi'
    
    os.chdir(sb)
    while True:
        fln=sc.recv(5)                      #read the name of the file
        print fln
        f = open(fln,'wb')                  #create the new file
        size = sc.recv(7)                   #receive the size of the file
        #size=size[:7]
        print size
        strng = sc.recv(int(size))          #receive the data of the file 
        #if strng:
        f.write(strng)                      #write the file
        f.close()
    sc.close()
    s.close()   
    


Answer: The parameter to
[`socket.recv`](http://docs.python.org/2/library/socket#socket.socket.recv)
only specifies the maximum buffer size for receiving data packages, it doesn't
mean exactly that many bytes will be read.

So if you write:

    
    
    strng = sc.recv(int(size))
    

you won't necessarily get all the content, specially if `size` is rather
large.

You need to read from the socket in a loop until you have actually read `size`
bytes to make it work.

