Reputation: 1
I am writing a socket programming with Python in order to send/receive a file over TCP.
While I am sending/receiving data, I figured out it neither sent nor received the part of files.
Here is a part to send a part of data based on the size of the buffer.
msg[i] = file[i].read()
file[i].close()
while 1:
tdata[i], msg[i] = msg[i][:buf], msg[i][buf:]
c.send(tdata[i])
if len(msg[i]) < buf:
break
Please help me out how to send/receive the whole data completely.
Upvotes: 0
Views: 1414
Reputation: 14863
I would try something like this:
import shutil
shutil.copyfileobj(open('data'), c.makefile('wb'))
This is how the SimpleHTTPServer module does it.
Upvotes: 0
Reputation: 20644
It will stop sending when len(msg[i]) < buf
, so the end of data may be missing.
If you want to send all of msg[i], it's better to do:
while msg[i]:
tdata[i], msg[i] = msg[i][:buf], msg[i][buf:]
c.sendall(tdata[i])
or just send it in one go:
c.sendall(msg[i])
Note that send()
will return how many bytes were actually sent (because it won't necessarily send all of them), so if you want to send all (which is usually the case) use sendall()
instead.
Upvotes: 3