1

I'm trying to send file from client to server in python. It is sending without any problem but I want to save that received file with same file name. I'm not getting idea how to save that file with same file name as it is sent from Client to Server.The code I've wrote for this is :

Client Code

import socket, os, shutil
from stat import ST_SIZE
HOST=raw_input("Please enter IP-address :  ")

PORT=int(raw_input("Please enter PORT Number : "))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
if s.recv(8)!='READY':
    raw_input('Unable to connect \n\n Press any key to exit ...')
    s.close()
    exit()
path=raw_input("Please enter the complete PATH of your file :  ")

f=open(path,'rb')
fsize=os.stat(f.name)[ST_SIZE]


s.sendall(str(fsize).zfill(8))
sfile = s.makefile("wb")
shutil.copyfileobj(f, sfile)
sfile.close()
s.close()
f.close()

Server Code

import socket
import shutil
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = ''
PORT = 23240
s.bind((HOST, PORT))
s.listen(3)
conn, addr = s.accept()               
print 'conn at address',addr
conn.sendall('READY')
i=1
f = open(r'file_'+ str(i)+".txt",'wb')
i=i+1

print 'File size',fsize
sfile = conn.makefile("rb")
shutil.copyfileobj(sfile, f)
sfile.close()

f.write(conn.recv(fsize))           
f.close()
conn.close()
s.close()
2
  • Why not just send f.name? Commented Apr 21, 2014 at 9:57
  • at client side, I've to enter complete path of the file. and receiver side, I want to receive that file with same name and same file type... Commented Apr 21, 2014 at 9:59

1 Answer 1

1

Your code is not very robust. recv(cnt) delivers up to cnt bytes of data, or less. So it's not sure, you read the whole file. It is even not sure, you get the "READY" in one recv. Instead, you have to use something like that:

def recv_all(sock, bufsize):
    result = ''
    while bufsize>0:
        data = sock.recv(min(bufsize, 4096))
        if not data:
            raise IOError("Socket closed")
        result += data
        bufsize -= len(data)
    return result

If you want to know the filename at the server, you also have to transfer it to the server, too. By the way, "READY" has 5 characters, not 8.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.