Transferring a file over sockets

Ferdinand Sousa ferdinandsousa at gmail.com
Wed Dec 17 07:11:46 EST 2008


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!!

Best regards,
Ferdi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081217/106ed0ec/attachment-0001.html>


More information about the Python-list mailing list