Client and Server program stuck after creating FTP connection - python

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.

Related

A request to receive data was disallowed, when creating a socket connection

I'm making a simple socket connection between server and client, when I want to receive data from the client, and write the data to a text file on the server Destkop, I'm getting an error on line 17 (data = sock.recv(1024)).
Error:
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
Server:
import socket
import os
import random
randomName = str(random.randint(100, 1001)) + 'data.txt'
FilePath = os.path.join(os.environ['USERPROFILE'], 'Desktop', randomName)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((socket.gethostname(), 9889))
sock.listen(1)
conn, addr = sock.accept()
print(f'{addr} has connected to the server.')
with open(FilePath, 'wb') as f:
if not f.writable():
pass
else:
data = sock.recv(1024)
f.write(data)
exit(0)
Client:
I'm trying to send my computer host name and key ( key is just a string )
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((socket.gethostname(), 9889))
fromServer = sock.recv(1024)
try:
sock.send(socket.gethostname() + key)
except:
print('Cant send hostname and key')
Your code makes a socket object, and binds it to an address at port 9889 as a socket server. When clients connect to this address with a socket connection, the server listens for data, and stores it in the “data” variable.
For receiving data, you should use the connection that was made and not the socket. Therefore:
data = sock.recv(1024)
You should replace sock with conn

'b' is getting passed when sending string from client to server in python while trying FTP implementation

I am trying to implement to implement FTP where I want to send Filename to server from client, I have tried below code, when I give file name as myText.txt but server is receiving as 'b"myText.txt'"
Can you please help me how can I get rid of b ?
This is the output on server:
This is server code:
import socket # Import socket module
port = 60000 # Reserve a port for your service.
socketObj = socket.socket() #Create a socket object
host = socket.gethostname() # Get local machine name
socketObj.bind((host, port)) # Bind to the port
socketObj.listen(5) # Now wait for client connectionection.
print ('Server listening....')
while True:
connection, addr = socketObj.accept() # Establish connectionection with client.
print ('Got connectionection from', addr)
data = connection.recv(1024)
print('Server received request for FTS of',(data))
filename=(repr(data))
f = open(filename,'rb')
l = f.read(1024)
while (l):
connection.send(l)
print('Sent ',repr(l))
l = f.read(1024)
f.close()
print('Done sending')
connection.send(('Thank you for connectionecting').encode())
connection.close()
This is the client code
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))
fileNeeded = input("What File do you need, please enter the name:")
s.send(fileNeeded.encode())
fileToBeSaved = input("Enter file name to save requested file")
with open(fileToBeSaved, 'wb') as f:
print ('file opened')
while True:
print('receiving data...')
data = s.recv(1024)
print((data))
if not data:
break
# write data to a file
f.write(data)
f.close()
print('Successfully got the file')
s.close()
print('connection closed')
The following is received in server:
Server received request for FTS of b'mytext.txt'
You can use the bytes.decode() method to convert bytes into a string:
Change:
filename=(repr(data))
to:
filename=repr(data).decode()

Connecting client and server in python the code below dont give output make browser busy

This code is not giving output it just makes the browser busy. Any idea why?
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect(('127.0.0.1', port))
print (s.recv(1024))
s.close
import socket
s=socket.socket()
host = socket.gethostname()
port = 12345
s.bind(('127.0.0.1', port))
s.listen(5)
while True:
c,addr = s.accept()
print ('Got connection from', addr)
c.send('Thank you for connecting')
c.close()
client program:
import socket
f=open("hello.txt","r").read()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12345
s.connect(('127.0.0.1', port))
s.sendall(str.encode(f))
print (s.recv(1024).decode('ascii'))
s.close()
server program:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
port = 12345
s.bind(('', port))
print ("socket binded to %s" %(port))
f=open("hi.txt","r").read()
s.listen(5)
print ("socket is listening")
while True:
c, addr = s.accept()
print ('Got connection from', addr)
print (c.recv(1024).decode('ascii'))
c.sendall(str.encode(f))
c.close()
server output:
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 51630)
helloooooo
client output:
hiiiii
Open the two programs in seperate shells.
Run server program first then client program.
Dont close the server program before running client program.
Create two files one for server and one for client.
Read the data from those files and send it.
While receiving the data decode it and print it.
You can send entire data from files or just a single line it depends on you.
To know more about reading,writing and creating files you can refer https://docs.python.org/release/3.6.5/tutorial/inputoutput.html#reading-and-writing-files
Let me know if it worked :)

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.

How to download file from local server in 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.

Categories