Search code examples
pythonfilesocketspython-2.7tcp

Sending a file over TCP sockets in Python


I've successfully been able to copy the file contents (image) to a new file. However when I try the same thing over TCP sockets I'm facing issues. The server loop is not exiting. The client loop exits when it reaches the EOF, however the server is unable to recognize EOF.

Here's the code:

Server

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.
s.bind((host, port))        # Bind to the port
f = open('torecv.png','wb')
s.listen(5)                 # Now wait for client connection.
while True:
    c, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr
    print "Receiving..."
    l = c.recv(1024)
    while (l):
        print "Receiving..."
        f.write(l)
        l = c.recv(1024)
    f.close()
    print "Done Receiving"
    c.send('Thank you for connecting')
    c.close()                # Close the connection

Client

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.

s.connect((host, port))
s.send("Hello server!")
f = open('tosend.png','rb')
print 'Sending...'
l = f.read(1024)
while (l):
    print 'Sending...'
    s.send(l)
    l = f.read(1024)
f.close()
print "Done Sending"
print s.recv(1024)
s.close                     # Close the socket when done

Here's the screenshot:

Server Server

Client Client

Edit 1: Extra data copied over. Making the file "not complete." The first column shows the image that has been received. It seems to be larger than the one sent. Because of this, I'm not able to open the image. It seems like a corrupted file.

File sizes

Edit 2: This is how I do it in the console. The file sizes are the same here. Python Console Same file sizes


Solution

  • Client need to notify that it finished sending, using socket.shutdown (not socket.close which close both reading/writing part of the socket):

    ...
    print "Done Sending"
    s.shutdown(socket.SHUT_WR)
    print s.recv(1024)
    s.close()
    

    UPDATE

    Client sends Hello server! to the server; which is written to the file in the server side.

    s.send("Hello server!")
    

    Remove above line to avoid it.