I am trying to implement a program which will enable an UDP server to send file requested by client and make a log of it after the file is sent in a particular directory.
Can anyone please guide me with Code to send file and make log of it in Python? also, we need to send data in chunks of 10 KB and $ at the end to announce that data is finished. If I try to run server side code: here is the error I am getting:
any help appreciated. Thanks in Advance.
Server Side :
import socket
import threading
import os
def RetrFile(name, sock):
filename = sock.recv(1024)
if os.path.isfile(filename):
sock.send("EXISTS " + str(os.path.getsize(filename)))
userResponse = sock.recv(1024)
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
sock.send("ERR ")
sock.close()
def Main():
host = '192.168.0.24'
port = 9090
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host,port))
s.listen(5)
print("Server Started.")
while True:
c, addr = s.accept()
print("client connedted ip:<" + str(addr) + ">")
t = threading.Thread(target=RetrFile, args=("RetrThread", c))
t.start()
s.close()
if __name__ == '__main__':
Main()
Client Side:
import socket
def Main():
host = '192.168.0.24'
port = 9090
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((host, port))
print("connected")
filename = raw_input("Filename? -> ")
if filename != 'q':
s.send(filename)
data = s.recv(1024)
if data[:6] == 'EXISTS':
filesize = long(data[6:])
message = raw_input("File exists, " + str(filesize) + "Bytes, download? (Y/N)? -> ")
if message == 'Y':
s.send("OK")
f = open('new_' + filename, 'wb')
data = s.recv(1024)
totalRecv = len(data)
f.write(data)
while totalRecv < filesize:
data = s.recv(1024)
totalRecv += len(data)
f.write(data)
print ("{0:.2f}".format((totalRecv / float(filesize)) * 100) + "% Done")
print("Download Complete!")
f.close()
else:
print ("File Does Not Exist!")
s.close()
if __name__ == '__main__':
Main()