sending a file through sockets
brueckd at tbye.com
brueckd at tbye.com
Thu Jul 4 18:12:57 EDT 2002
On Thu, 4 Jul 2002, Guyon Morée wrote:
> so the trick is to convert a file to a string representation right?
> i still have to try it out, but maybe you can confirm my way of thinking
> here :)
Um... you *could* do that, but it wouldn't actually help at all. The
contents of the file already are in a string representation because Python
strings can contain anything, including binary characters. The easiest way
to send a file is to simply read the data from the file and send it out
the socket, but to send the length of the file first so the receiving end
knows if and when it got the whole thing. If you need too much more
functionality than this it might be easier to just use one of the standard
file transfer protocols, e.g. FTP. Anyway, here's some sample code, but if
you're not already familiar with sockets then you should spend a little
time experimenting with them.
The sending side listens for incoming connections and sends out the file.
The receiving side connects to the "server" and writes the file to disk.
Common code:
import struct
PORT = 5555
FILENAME = 'foo.bin'
HDR = '!I'
HDR_SZ = struct.calcsize(HDR)
Sending side:
import os
from socket import *
s = socket(AF_INET,SOCK_STREAM)
s.bind(('',PORT))
s.listen(1)
while 1:
q,v = s.accept()
q.sendall(struct.pack(HDR, os.path.getsize(FILENAME)))
f = open(FILENAME,'rb')
while 1:
data = f.read(4096)
if not data: break
q.sendall(data)
q.close()
Receiving side:
from socket import *
f = open(FILENAME, 'wb')
s = socket(AF_INET, SOCK_STREAM)
s.connect(('', PORT))
size = s.recv(HDR_SZ)
size = struct.unpack(HDR, size)
while size > 0:
data = s.recv(4096)
if not data: break
size -= len(data)
f.write(data)
s.close()
Note that if you're not using Python 2.2 or later there isn't a sendall
method in socket objects so the sending side should check the return value
from send() to see how many bytes were actually written out and resend any
that didn't make it.
-Dave
More information about the Python-list
mailing list