python - How to send file from Client to Server and save it with same filename? -


i'm trying send file client server in python. sending without problem want save received file same file name. i'm not getting idea how save file same file name sent client server.the code i've wrote :

client code

import socket, os, shutil 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 connect \n\n press key exit ...')     s.close()     exit() path=raw_input("please enter complete path of 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 @ 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() 

your code not robust. recv(cnt) delivers cnt bytes of data, or less. it's not sure, read whole file. not sure, "ready" in 1 recv. instead, have use 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 want know filename @ server, have transfer server, too. way, "ready" has 5 characters, not 8.


Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -