Why isn't my client receiving my file from the server? - python

I've created a fairly simple server with the aim of sending a simple .txt file but it won't send for some reason.
Server code:
import socket
port = 8081
host = "192.168.0.20"
s = socket.socket()
s.bind((host, port))
s.listen(5)
print("Server Listening.....")
while True:
conn, addr = s.accept()
print("Got connection from", addr)
data = conn.recv(1024)
print("Data recieved", repr(data))
filename = "/Users/dylanrichards/Desktop/keysyms.txt"
f = open(filename, 'rb')
l = f.read(1024)
while (l):
conn.send(l)
print("Sent", repr(l))
l = f.read(1024)
f.close()
print("Done sending")
conn.send("Thank you for connecting")
conn.close()
Here is the code for the client:
import socket
port = 8081
host = "192.168.0.20"
s = socket.socket()
s.connect((host, port))
with open("Recieved_File", 'wb') as f:
print("File opened")
while True:
print("Receiving data...")
data = s.recv(1024)
print("Data=%s", (data))
if not data:
break
f = open("/Users/dylanrichards/Desktop/test12.txt")
f.write(data)
f.close()
print("Successfully got file")
print("Connection closed")
s.close()
Im testing this over my Local Network on a Macbook Air if thats any help. Thanks in advance...

Multiple file handles opened and all has same variable f
with open("Recieved_File", 'wb') as f: -- I think this is not required.
f = open("/Users/dylanrichards/Desktop/test12.txt")should be outside while loop.
While opening above file, add mode as 'wb'
Client Code :
import socket
port = 8081
host = "192.168.0.20"
s = socket.socket()
s.connect((host, port))
f = open("/Users/dylanrichards/Desktop/test12.txt",'wb')
while True:
print("Receiving data...")
data = s.recv(1024)
if not data:
break
print("Data=%s", (data))
f.write(data)
f.close()
print("Successfully got file")
print("Connection closed")
s.close()

Related

Hello everyone, I am trying to receive all the data coming from a server but the loop does not stop

So here is the code hangs on the while loop.
client.py:
import socket
ip = "127.0.0.7"
port = 65000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((ip, port))
while True:
file = input("Filename:")
s.sendall(file.encode())
b = b""
while True:
data = s.recv(4096)
if not data:
break
b+=data
with open(file, "wb") as f:
f.write(donne)
break
server.py:
import socket
import os
ip = "127.0.0.7"
port = 65000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((ip, port))
s.listen(5)
conn, addr = s.accept()
while True:
receive = conn.recv(1024).decode()
if os.path.exists(receive):
with open(receive, "rb") as f:
data = f.read()
conn.sendall(data)
break
else:
print("File not found")
The problem is with the client code.
I would like to receive all the data and write them to a file but the loop in client.py does not stop.

Server and client don't send file, how can I make it work?

I'm trying to create a client-server file transfer using python socket but i cant make it work
For example I used this from a tutorial:
Server:
import socket, os, sys
def Main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
print(IP)
host = IP
port = 50001
s = socket.socket()
s.bind((host,port))
print("server Started")
s.listen(1)
while True:
c, addr = s.accept()
print("Connection from: " + str(addr))
filename = ''
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
filename += data
print("from connected user: " + filename)
c.close()
if __name__ == '__main__':
Main()
Client:
host = '192.168.1.90'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = 'prova3.txt'
s.send(Filename.encode('utf-8'))
s.shutdown(socket.SHUT_WR)
data = s.recv(1024).decode('utf-8')
print(data)
s.close()
host = '192.168.1.90'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = 'prova3.txt'
s.send('prova3.txt')
s.shutdown(socket.SHUT_WR)
data = s.recv(1024).decode('utf-8')
print(data)
s.close()
Now this client and server connect to each other but don't send file, what's wrong?

Send big file over socket

I have a video file and want to send it over socket. Video is send to the client but video is not playable and also video size received is 2 KB. And acutely video size is 43 MB. What is the problem?
Server:
import socket
try:
soc = socket.socket()
print('socked created.')
host = ''
port = 8080
soc.bind((host, port))
print('soc bound.')
soc.listen(10)
print('waiting for connecting...')
con, addr = soc.accept()
print('server connected to IP: ' + addr[0] + " port: " + str(addr[1]))
while True:
filename = input('enter filename: ')
file = open(filename, 'rb')
sendfile = file.read(9000000)
con.send(sendfile)
print("file has been send.")
break
con.close()
soc.close()
except socket.error as err:
print('error ', str(err))
client:
import socket
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socked created. waiting for connecting to server...')
server_address = ("192.168.1.3", 8080)
soc.connect(server_address)
print('connected to the server.')
while True:
recvfile = soc.recv(9000000)
savefilebyname = input("enter file name: ")
openfile = open(savefilebyname, 'wb')
openfile.write(recvfile)
openfile.close()
break
print("File has been received.")
soc.close()
Check the return value of send and recv. The 9000000 value is a maximum but not guaranteed value to send/recv. Alternatively, use sendall.
For recv, you have to loop until you receive all the data. If you close the socket after the file is sent, recv will return zero when all the data is received.
FYI, your while True: in both files never loops due to the break, so they are unnecessary.
Here's something that should work...
server.py
import socket
soc = socket.socket()
soc.bind(('',8080))
soc.listen(1)
print('waiting for connection...')
with soc:
con,addr = soc.accept()
print('server connected to',addr)
with con:
filename = input('enter filename to send: ')
with open(filename, 'rb') as file:
sendfile = file.read()
con.sendall(sendfile)
print('file sent')
client.py
import socket
soc = socket.socket()
soc.connect(('localhost',8080))
savefilename = input("enter file name to receive: ")
with soc,open(savefilename,'wb') as file:
while True:
recvfile = soc.recv(4096)
if not recvfile: break
file.write(recvfile)
print("File has been received.")

How to continuously send images from raspberry to pc without delay?

I'm trying to send webcam captured images from pi to pc, but while using socket programming for it, i'm getting a significant amount of delay (about 5-6 seconds per image). Am I doing something wrong over here? Is there a way to reduce this delay or any other better technique to send the data to pc with minimum delay?
Server side:
import socket
port = 60000
s = socket.socket()
host = ""
s.bind((host, port))
s.listen(5)
print('Server listening....')
while True:
conn, addr = s.accept()
print 'Got connection from', addr
data = conn.recv(1024)
print('Server received', repr(data))
filename='mytext.txt'
f = open(filename,'rb')
l = f.read(1024)
while (l):
conn.send(l)
print('Sent ',repr(l))
l = f.read(1024)
f.close()
print('Done sending')
conn.send('Thank you for connecting')
conn.close()
Client:
import socket # Import socket module
import time
s = socket.socket() # Create a socket object
host = "192.1.1.1" #Ip address that the TCPServer is there
port = 60000 # Reserve a port for your service.
s.connect((host, port))
s.send("Hello server!")
with open('received_file.png', 'wb') as f:
print 'file opened'
start = time.time()
while True:
# print('receiving data...')
data = s.recv(1024)
# print('data=%s', (data))
if not data:
break
# write data to a file
f.write(data)
print(time.time() - start)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')

How to send files in "chunks" by socket?

I'm trying to send a large file (.avi) over socket by sending the content of the file in chunks (a little bit like torrents). The problem is that the script doesn't send the file. I'm out of ideas here.
Any help or twerking of the script would be very appreciated.
Server:
import socket
HOST = ""
PORT = 8050
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(1)
conn, addr = sock.accept()
print("Connected by ", str(addr))
while 1:
data = conn.recv(1024)
if data.decode("utf-8") == 'GET':
with open(downFile,'rb') as output:
l = output.read(1024)
while (l):
conn.send(l)
l = output.read(1024)
output.close()
conn.close()
Client:
import socket
HOST = "localhost"
PORT = 8050
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST,PORT))
while 1:
message = input()
sock.send(bytes(message,'UTF-8'))
conn.send(str.encode('GET'))
with open(downFile, 'wb+') as output:
while True:
rec = str(sock.recv(1024), "utf-8")
if not rec:
break
output.write(rec)
output.close()
print('Success!')
sock.close()
Here are a working client and server that should demonstrate transferring a file over a socket. I made some assumptions about what your code was supposed to do, for example, I assumed that the initial message the client sent to the server was supposed to be the name of the file to download.
The code also includes some additional functionality for the server to return an error message to the client. Before running the code, make sure the directory specified by DOWNLOAD_DIR exists.
Client:
import socket
import sys
import os
HOST = "localhost"
PORT = 8050
BUF_SIZE = 4096
DOWNLOAD_DIR = "downloads"
def download_file(s, down_file):
s.send(str.encode("GET\n" + down_file))
rec = s.recv(BUF_SIZE)
if not rec:
return "server closed connection"
if rec[:2].decode("utf-8") != 'OK':
return "server error: " + rec.decode("utf-8")
rec = rec[:2]
if DOWNLOAD_DIR:
down_file = os.path.join(DOWNLOAD_DIR, down_file)
with open(down_file, 'wb') as output:
if rec:
output.write(rec)
while True:
rec = s.recv(BUF_SIZE)
if not rec:
break
output.write(rec)
print('Success!')
return None
if DOWNLOAD_DIR and not os.path.isdir(DOWNLOAD_DIR):
print('no such directory "%s"' % (DOWNLOAD_DIR,), file=sys.stderr)
sys.exit(1)
while 1:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except Exception as e:
print("cannot connect to server:", e, file=sys.stderr)
break
file_name = input("\nFile to get: ")
if not file_name:
sock.close()
break
err = download_file(sock, file_name)
if err:
print(err, file=sys.stderr)
sock.close()
Server:
import socket
import sys
import os
HOST = ""
PORT = 8050
BUF_SIZE = 4096
def recv_dl_file(conn):
data = conn.recv(1024)
if not data:
print("Client finished")
return None, None
# Get command and filename
try:
cmd, down_file = data.decode("utf-8").split("\n")
except:
return None, "cannot parse client request"
if cmd != 'GET':
return None, "unknown command: " + cmd
print(cmd, down_file)
if not os.path.isfile(down_file):
return None, 'no such file "%s"'%(down_file,)
return down_file, None
def send_file(conn):
down_file, err = recv_dl_file(conn)
if err:
print(err, file=sys.stderr)
conn.send(bytes(err, 'utf-8'))
return True
if not down_file:
return False # client all done
# Tell client it is OK to receive file
sent = conn.send(bytes('OK', 'utf-8'))
total_sent = 0
with open(down_file,'rb') as output:
while True:
data = output.read(BUF_SIZE)
if not data:
break
conn.sendall(data)
total_sent += len(data)
print("finished sending", total_sent, "bytes")
return True
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(1)
keep_going = 1
while keep_going:
conn, addr = sock.accept()
print("Connected by", str(addr))
keep_going = send_file(conn)
conn.close() # close clien connection
print()
sock.close() # close listener

Categories

Resources