Search code examples
pythonsocketsfile-transfer

socket programming for transferring a photo in python


I'm new to socket programming in python. Here is an example of opening a TCP socket in a Mininet host and sending a photo from one host to another. In fact I have changed the code which I used to send a simple message to another host (writing the received data to a text file) in order to meet my requirements. But when I run this code, I encounter this error at sender side:

144
Traceback (most recent call last):
  File mmyClient2,pym, line 13, in <module> 
    if(s.sendall(data)):
  File m/usr/lib/python2.7/socket.pym, line 228, in meth
    return yetattr[self,_sockename](*args) 
  File m/usr/lib/python2.7/socket.pym, line 174, in _dummy 
    raise error(EBADF, 'Bad file descriptor') 
socket,error: [Errno 9] Bad file descriptor  

So what's wrong?

Receiver.py

import socket
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('10.0.0.1', 12345))

buf = 1024
f = open("2.jpg",'wb')

s.listen(1)
conn , addr = s.accept()
while 1:
    data = conn.recv(buf)
    print(data[:10])
    #print "PACKAGE RECEIVED..."
    f.write(data)   
    if not data: break
    #conn.send(data)
conn.close()
s.close()

Sender.py:

import socket
import sys

f=open ("1.jpg", "rb")
print sys.getsizeof(f)
buf = 1024
data = f.read(buf)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.1',12345))

while (data):
    if(s.sendall(data)):
        #print "sending ..."
        data = f.read(buf)
        #print(f.tell(), data[:10])
s.close()

There seems to be a problem with s.sendall(), because when I change it to s.send(), there is no error and photo transfer is successful. So my question is: Although I was suggested to use s.sendall() instead of s.send() in my previous question on this site, Is it wrong not to do this?


Solution

  • After send all data, you closed socket.And use closed socket again, that cause error.You can write sender like this.

    import socket
    import sys
    
    f=open ("1.jpg", "rb")
    print sys.getsizeof(f)
    buf = 1024
    data = f.read(buf)
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('10.0.0.1',12345))
    
    while 1:
        if not data:
            break
        s.sendall(data)
        data = f.read(buf)
    s.close()