Reputation: 33243
I found the code here: Send a file through sockets in Python (the selected answer)
But I will jut post it here again..
server.py
import socket
import sys
s = socket.socket()
s.bind(("localhost",9999))
s.listen(10)
while True:
sc, address = s.accept()
print address
i=1
f = open('file_'+ str(i)+".txt",'wb') #open in binary
i=i+1
while (True):
l = sc.recv(1024)
while (l):
print l #<--- i can see the data here
f.write(l) #<--- here is the issue.. the file is blank
l = sc.recv(1024)
f.close()
sc.close()
s.close()
client.py
import socket
import sys
s = socket.socket()
s.connect(("localhost",9999))
f=open ("test.txt", "rb")
l = f.read(1024)
while (l):
print l
s.send(l)
l = f.read(1024)
s.close()
On server code, the print l line prints the file contents..so that means that content is being transferred.. but then the file is empty??
what am i missing? thanks
Upvotes: 2
Views: 1506
Reputation: 4903
Well that server code didn't work anyway, I've modified it to get it working.
The file was empty because it was stuck in the while True
and never got around to closing the file.
Also i=1
was inside the loop so it was always writing to the same file.
import socket
import sys
s = socket.socket()
s.bind(("localhost",9999))
s.listen(10)
i=1
while True:
print "WILL accept"
sc, address = s.accept()
print "DID accept"
print address
f = open('file_'+ str(i)+".txt",'wb') #open in binary
i += 1
l = sc.recv(1024)
while (l):
f.write(l) #<--- here is the issue.. the file is blank
l = sc.recv(1024)
f.close()
sc.close()
print "Server DONE"
s.close()
Upvotes: 2
Reputation: 4325
You are probably trying to inspect the file while the program is running. The file is being buffered, so you likely won't see any output in it until the f.close()
line is executed, or until a large amount of data is written. Add a call to f.flush()
after the f.write(l)
line to see output in real time. Note that it will hurt performance somewhat.
Upvotes: 4