Transferring a file over sockets

MRAB google at mrabarnett.plus.com
Wed Dec 17 10:21:02 EST 2008


Hendrik van Rooyen wrote:
> Ferdinand Sousa  wrote:
> 
>> ==========================================================
> .# 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))
> 
> This recv is not guaranteed to actually receive the number of
> characters you are asking for - it will stop when it has received that
> many, yes, but it may return with less, or even none if there is a 
> time out set.
> 
> The TCP is a more or less featureless stream of characters.
> 
> Consider including a start marker so you know where the lesson starts.
> If you do this, consider the possibility of having a "false sync".
> Sending/receiving  the length is good - also google for "netstring"
> Google for "escaping".
> 
> Consider writing a loop to receive until the required length has been
> received - look at the docs for the recv function - it can tell you how 
> much has been received.
> 
>> 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())
> 
> Are you sure that the send will send all the chars
> that you ask it to send?
> 
> If yes - why do you think this?
> 
> What are the values that the send can return?
> 
>> s.close()
>> f.close()
>>
>> ===========================================================
> 
You're also sending the length as a bytestring str(fsize), which will 
have an unknown length, but you're receiving the length as exactly 8 
bytes. Either mark the end of the length in some way (with '\n'?) and 
look for that when receiving, or pad what you send to exactly 8 bytes 
(str(fsize).zfill(8)).



More information about the Python-list mailing list