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

五迷三道 提交于 2019-12-11 08:48:17

问题


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()

回答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.



来源:https://stackoverflow.com/questions/23194388/how-to-send-file-from-client-to-server-and-save-it-with-same-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!