2

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

Community
  • 1
  • 1
frazman
  • 32,081
  • 75
  • 184
  • 269
  • Are your indents correct? I don't see how it ever breaks out of your middle ``while True`` even when it's read all the data from the client socket it's stuck in that loop. – sotapme Feb 10 '13 at 21:59
  • @sotapme: Yeah. i feel that so. I copied over the code from here http://stackoverflow.com/questions/9382045/send-a-file-through-sockets-in-python (the selected answer) I am figuring out the right indents. Please let me know incase you figured it out. Thanks – frazman Feb 10 '13 at 22:05
  • 1
    To my mind that middle ``while True`` is unnecessary, surely when you run the code it prints blanks lines forever when it's copied the file across. – sotapme Feb 10 '13 at 22:17

2 Answers2

4

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.

Krzysztof Kosiński
  • 4,225
  • 2
  • 18
  • 23
2

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()
sotapme
  • 4,695
  • 2
  • 19
  • 20