Transferring a file over sockets

Jean-Paul Calderone exarkun at divmod.com
Wed Dec 17 08:52:36 EST 2008


On Wed, 17 Dec 2008 17:41:46 +0530, Ferdinand Sousa <ferdinandsousa at gmail.com> wrote:
>I am using sockets to transfer a file over LAN. There are 2 scripts, the
>server opens a listens for connection and the client is run on another
>machine. I always make sure the server is run first. The strange thing is
>that if the the server script is double-clicked and executed (run in a
>console with title %Python path%python.exe) the output file saved on the
>server is truncated. It works just fine if you open the server script in
>IDLE and then run it. The client script can be run in either way, it still
>works. You could try using any arbitrary file to test this behaviour after
>changing the file name in both the scripts.
>
>==========================================================
># file receiver
># work in progress
>
>import socket
>
>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>HOST = '192.168.1.17'
>PORT = 31400
>
>s.bind((HOST, PORT))
>s.listen(3)
>conn, addr = s.accept()
>print 'conn at address',addr
>conn.send('READY')
>f = open('C:\\Documents and Settings\\USER\\Desktop\\test.pdf','wb')
>fsize=int(conn.recv(8))
>print 'File size',fsize
>f.write(conn.recv(fsize))
>f.close()
>conn.close()
>s.close()
>
>raw_input('Press any key to exit')
>
>
>===========================================================
>
># file sender !!!
># Work in progress
>
>import socket, os
>from stat import ST_SIZE
>
>
>HOST = '192.168.1.17'
>PORT = 31400              # Arbitrary non-privileged port
>
>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>
>s.connect((HOST,PORT))
>if s.recv(5)!='READY':
>    raw_input('Unable to connect \n\n Press any key to exit ...')
>    s.close()
>    exit()
>
>f=open('C:\\Documents and Settings\\USER\\Desktop\\t.pdf', 'rb')
>fsize=os.stat(f.name)[ST_SIZE]
>
>s.send(str(fsize))
>s.send(f.read())
>
>s.close()
>f.close()
>
>===========================================================
>
>Thanks for reading!!

You're not handling your sockets properly.  send() does not necessary
send the entire string you pass to it.  recv(n) does not necessarily
return an n-length string.  Read the socket documentation more carefully
and try fixing those issues.  Or try using Twisted which presents a
somewhat easier API to use.

Jean-Paul



More information about the Python-list mailing list