How to download file from local server in Python - python

Scenario is:
Client will Enter a file name e.g xyz
Server will show all the files that it have in different folders.
Client will select 1 or 2 or 3 (if there).
and file will be downloaded.
I have done searching part. I want help in downloading and saving the file in any other directory.
My code so far is for searching the file.
import socket
tcp_ip="127.0.0.1"
tcp_port=1024
buffer_size= 200
filename=raw_input("Enter file name\n")
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((tcp_ip,tcp_port))
data=s.recv(buffer_size)
s.close()
Server Code : (This code is now for one file) The required help is how to download and save that file which is found at server.
import socket
import os
tcp_ip='127.0.0.1'
tcp_port=1024
buffer_size=100
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((tcp_ip, tcp_port))
s.listen(1)
conn, addr = s.accept()
print 'Connection Address:',addr
while 1:
data=conn.recv(buffer_size)
if not data:
break
else:
print "received server side data:", data
conn.send(data)
conn.close()

Following is the example which shows how to download a file from a server over tcp.
Client Code:
import socket
import os
HOST = 'localhost'
PORT = 1024
downloadDir = "/tmp"
filename = raw_input('Enter your filename: ')
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(filename)
with open(os.path.join(downloadDir, filename), 'wb') as file_to_write:
while True:
data = socket1.recv(1024)
if not data:
break
file_to_write.write(data)
file_to_write.close()
socket1.close()
Server Code:
import socket
HOST = 'localhost'
PORT = 1024
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(1)
while (1):
conn, addr = socket.accept()
reqFile = conn.recv(1024)
with open(reqFile, 'rb') as file_to_send:
for data in file_to_send:
conn.sendall(data)
conn.close()
socket.close()
Note: server code is not robust and will crash when file doesn't exists. You should modify above example according to your needs.

Related

Client and Server program stuck after creating FTP connection

I have two programs, one for the client and one for the server. I am trying to establish an FTP connection between them to transfer files. The two programs connect okay and I get a confirmation from the server that it has connected to the client's ip, but I get no more output from either program.
Client:
# client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 60000 # Reserve a port for your service.
s.connect((host, port))
with open('received_file', 'wb') as f:
print ('file opened')
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)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')
Server:
# server.py
import socket # Import socket module
port = 60000 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print ('Server listening....')
while True:
conn, addr = s.accept() # Establish connection with client.
print ('Got connection from', addr)
data = conn.recv(1024)
print('Server received', repr(data))
filename='text.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()
I receive this output from the server:
Server listening....
Got connection from ('192.168.56.1', 51059)
And this from the client:
file opened
receiving data...
But neither program moves past this stage. I'm not sure where in the code that the problem is coming from.

Why Python Socket works only on local network?

I'm trying to send a text file trhough Python sockets and it works but only on local network. Why is that?(I'm working with Python 3.6)
This is the server.py:
import socket
HOST = '0.0.0.0'
PORT = 80
ADDR = (HOST,PORT)
BUFSIZE = 4096
print(socket.gethostbyname(socket.gethostname()))
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.bind(ADDR)
serv.listen(5)
print ('listening ...')
while True:
conn, addr = serv.accept()
print ('client connected ... ', addr)
myfile = open('asd.txt', 'w')
while True:
data = conn.recv(BUFSIZE)
if not data: break
myfile.write(data.decode("utf-8"))
print ('writing file ....')
myfile.close()
print ('finished writing file')
conn.close()
print ('client disconnected')
This is the client.py:
import socket
HOST = '192.168.2.109'
PORT = 80
ADDR = (HOST,PORT)
BUFSIZE = 4096
textfile = "C:/Users/Public/asd.txt"
bytes = open(textfile, "r").read()
print (len(bytes))
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect_ex(ADDR)
client.send(bytes.encode())
client.close()
I've tried this and it worked on local network, but when I sent to my friend the client to try it, it just printed out the bytes but didn't connect to my server.(The server was running on my pc)
If the client and host are connected to the same network(LAN) i.e through same router or a hotspot, then the above code will work. If you want to do something like, run server.py on a PC connected to your WiFi and run client.py on a laptop connected through dongle you will have to use port-forwarding.

TCP client server not receiving any data from each other

I have written the following TCP client and server using python socket module. However, after I run them, no output is being given. It seems that
the program is not able to come out of the while loop in the recv_all method
Server:
import socket
def recv_all(sock):
data = []
while True:
dat = sock.recv(18)
if not dat:
break
data.append(dat)
return "".join(data)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '127.0.0.1'
PORT = 45678
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(1)
print "listening at", sock.getsockname()
while True:
s, addr = sock.accept()
print "receiving from", addr
final = recv_all(s)
print "the client sent", final
s.sendall("hello client")
s.close()
Client :
import socket
def recv_all(sock):
data=[]
while True:
dat=sock.recv(18)
if not dat:
break
data.append(dat)
return "".join(data)
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
PORT=45678
HOST='127.0.0.1'
sock.connect((HOST,PORT))
sock.sendall("hi server")
final=recv_all(sock)
print "the server sent",final
Because in server file you use an endless loop in another. I suggest you to edit recv_all method in both files this way:
def recv_all(sock):
data = []
dat = sock.recv(18)
data.append(dat)
return "".join(data)
But after edit like this your server stays on until KeyInterrupt, while you should run client file everytime you want to send data. If you want an automatically send/receive between server and client, I offer you try threading.

Python stream file

I want to stream a file (mp3) in python. I've written the server code (which doesn't work):
import socket
HOST = ''
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
s.bind((HOST, PORT))
print 'Socket bind complete'
s.listen(1)
print 'Socket now listening'
conn, addr = s.accept()
data = open("song.mp3", "rb")
data = data.read()
conn.sendall(data)
I haven't written a client for it, as I wanted to make it work with VLC, Chrome and other music players. When trying in VLC it gives me a "Connection reset by peer" error, whereas in Chrome it gives a "Broken pipe" error.
What I'm trying to do is make a basic replica of AirPlay, but I don't know what's wrong.
Have a look at this
Playing remote audio files in Python?
The mp3 format was designed for streaming, which makes some things simpler than you might have expected. The data is essentially a stream of audio frames with built-in boundary markers, rather than a file header followed by raw data, have a look at following url for more information.
Writing a Python Music Streamer
OK, I got it to work with VLC by using HTTP here's the code:
import socket
filePath = "/storage/sdcard0/Music/song.mp3"
fileData = open(filePath, "rb").read()
host = ''
port = 8808
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HTTPString = "HTTP/1.1 200 OK\r\nConnection: Keep-Alive\r\nContent-Type: audio/mpeg\r\n\r\n" + fileData
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
conn.sendall(HTTPString)
UPDATE: Got it to work with Chrome's (never thought I'd say this) stupid persistent connections, which raise SIGPIPE, so I just ignore it:
import socket
filePath = "/storage/sdcard0/Music/Madonna - Ray Of Light.mp3"
fileData = open(filePath, "rb").read()
host = ''
port = 8808
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HTTPString = "HTTP/1.1 200 OK\r\nConnection: Keep-Alive\r\nContent-Type: audio/mpeg\r\n\r\n" + fileData
s.bind((host, port))
s.listen(10)
while 1:
try:
conn, addr = s.accept()
conn.sendall(HTTPString)
except socket.error, e:
pass

client-server chat python error

I'm trying the following client and server chat program. Although I get an error whenever I try to run the server program, when the client program runs it stays on a blank screen not allowing me to type anything. I've tried running server first and running client first and I get the same results. I can't read the error from the server program because it flashes the error and closes the window. Here is my code:
server:
#server
import socket
import time
HOST = ''
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
client:
#client
import socket
import time
HOST = "localhost"
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((HOST,PORT))
s.sendall('Helloworld')
data = s.recv(1024)
s.close()
print 'Recieved', repr(data)
Im not an expert but I was able to make your examples work by changing the socket from datagram to stream connection, and then encoding message being sent because strings aren't supported (although this might not effect you since I think that change was made in Python 3...I'm not 100% sure).
I believe the main issue is that you're trying to listen() but SOCK_DGRAM (UDP) doesn't support listen(), you just bind and go from there, whereas SOCK_STREAM (TCP) uses connections.
If you're just trying to get the program going, use the below code, unless there is a specific reason you'd like to use SOCK_DGRAM.
The code is below:
client
#client
import socket
import time
HOST = "localhost"
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
test = 'Helloworld'
s.sendall(test.encode())
data = s.recv(1024)
s.close()
print 'Recieved', repr(data)
server
#server
import socket
import time
HOST = ''
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connected by', addr)
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()

Categories