Receive Image using socket programming in Python - python

I am trying to receive an image in python to use it in my program.
Here is the sever code:
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("127.0.0.1", 5005))
server_socket.listen(5)
data = ' '
client_socket, address = server_socket.accept()
print "Conencted to - ",address,"\n"
while (1):
data = client_socket.recv(1024)
print "The following data was received - ",data
print "Opening file - ",data
img = open(data,'r')
while True:
strng = img.readline(512)
if not strng:
break
client_socket.send(strng)
img.close()
print "Data sent successfully"
exit()
#data = 'viewnior '+data
#os.system(data)
And here is the client code:
import socket,os
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("127.0.0.1", 5005))
size = 1024
while(1):
print "Enter file name of the image with extentsion (example: filename.jpg,filename.png or if a video file then filename.mpg etc) - "
fname = raw_input()
client_socket.send(fname)
#fname = 'documents/'+fname
fp = open(fname,'w')
while True:
strng = client_socket.recv(512)
if not strng:
break
fp.write(strng)
fp.close()
print "Data Received successfully"
exit()
#data = 'viewnior '+fname
#os.system(data)
The received should now be read to be able to use it. I am opening it like this:
input_image = Image.open('data').convert('L').resize((100, 100))
but when I run both codes in cmd the output is:
The following data was received - + path Opening file - + path
Then nothing happens although the image should be used and the final output should be shown.
Anyone can help?

I don't know if this is your (only) problem, but when working with binary files, you should pass the b flag to the built-in function open:
img = open(data, 'rb')

Related

How to transfer more files rather than just one using python?

I made a file transferrer and the problem is that out of unknown reason it lets me only send one file... When I try the second time the program works fine, but the file doesn't show up in directory. It would mean a lot to me if someone helped me out.
Code for sender:
import os
import shutil
import socket
import time
# Creating a socket.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((socket.gethostname(), 22222))
sock.listen(5)
print("Host Name: ", sock.getsockname())
# Accepting the connection.
client, addr = sock.accept()
original = ""
print("When you want to stop with file uploading type -> STOP <-")
while (1):
original = input(str("Filepath:"))
if (original!="STOP"):
filename = os.path.basename(original)
target = r'C:\Users\Gasper\Desktop\transfer\filename'
path = target.replace('filename', filename)
new_file = shutil.copy(original, path)
# Getting file details.
file_name = filename
file_size = os.path.getsize(file_name)
# Sending file_name and detail.
client.send(file_name.encode())
client.send(str(file_size).encode())
# Opening file and sending data.
with open(file_name, "rb") as file:
c = 0
# Running loop while c != file_size.
while c <= file_size:
data = file.read(1024)
if not data:
break
client.sendall(data)
c += len(data)
os.remove(filename)
else:
break
print("File Transfer Complete!")
input("Press enter to exit...")
# Closing the socket.
sock.close()
Code for receiver:
import socket
import time
host = input("Host Name: ")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Trying to connect to socket.
try:
sock.connect((host, 22222))
print("Connected Successfully")
except:
print("Unable to connect")
exit(0)
# Send file details.
file_name = sock.recv(100).decode()
file_size = sock.recv(100).decode()
# Opening and reading file.
with open("./rec/" + file_name, "wb") as file:
c = 0
# Starting the time capture.
start_time = time.time()
# Running the loop while file is recieved.
while c <= int(file_size):
data = sock.recv(1024)
if not data:
break
file.write(data)
c += len(data)
# Ending the time capture.
end_time = time.time()
print("File transfer Complete!")
input("Press enter to exit...")
# Closing the socket.
sock.close()
Example:
Filepath: C\Users\Admin\Desktop\Directory\File1.txt(I put in the first file path and it transfers successfully)
Filepath: C\Users\Admin\Desktop\Directory\File2.txt(I put in the second file path and it doesnt transfer at all)

Tcp sockets to send and receive files, using python

I am trying to make simple client server program to send and receive file form server using tcp sockets. As far as getting files from server is not an issue, server creates a file with the same name and put data in that file but when it comes to putting files to server,sometimes it works great but always chance so mostly server is getting file name along with file contents and instead of writing that to file, it writes both filename and contents as new file name and that file remains empty. Will be great help if someone can suggest any solution.
server.py
import socket
import sys
HOST = 'localhost'
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(1)
while (1):
conn, addr = socket.accept()
print 'New client connected ..'
reqCommand = conn.recv(1024)
print 'Client> %s' %(reqCommand)
if (reqCommand == 'quit'):
break
#elif (reqCommand == lls):
#list file in server directory
else:
string = reqCommand.split(' ', 1) #in case of 'put' and 'get' method
reqFile = string[1]
if (string[0] == 'put'):
with open(reqFile, 'wb') as file_to_write:
data=conn.recv(1024)
while True:
if not data:
break
else:
file_to_write.write(data)
data=conn.recv(1024)
file_to_write.close()
break
print 'Receive Successful'
elif (string[0] == 'get'):
with open(reqFile, 'rb') as file_to_send:
for data in file_to_send:
conn.sendall(data)
print 'Send Successful'
conn.close()
socket.close()
client.py
import socket
import sys
HOST = 'localhost' # server name goes in here
PORT = 3820
def put(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open('clientfolder/'+inputFile, 'rb') as file_to_send:
data=file_to_send.read(1024)
while(data):
socket1.send(data)
data=file_to_send.read(1024)
file_to_send.close()
print 'PUT Successful'
socket1.close()
return
def get(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open('clientfolder/'+inputFile, 'wb') as file_to_write:
while True:
data = socket1.recv(1024)
# print data
if not data:
break
# print data
file_to_write.write(data)
file_to_write.close()
print 'GET Successful'
socket1.close()
return
msg = raw_input('Enter your name: ')
while(1):
print 'Instruction'
print '"put [filename]" to send the file the server '
print '"get [filename]" to download the file from the server '
print '"ls" to list all files in this directory'
print '"lls" to list all files in the server'
print '"quit" to exit'
sys.stdout.write('%s> ' % msg)
inputCommand = sys.stdin.readline().strip()
if (inputCommand == 'quit'):
socket.send('quit')
break
# elif (inputCommand == 'ls')
# elif (inputCommand == 'lls')
else:
string = inputCommand.split(' ', 1)
if (string[0] == 'put'):
put(inputCommand)
elif (string[0] == 'get'):
get(inputCommand)
#current working directory is server location
#get will get file from current directory to clientfolder directory.
TCP is a streaming protocol, so you have to design message breaks into your protocol. For example:
s.send('put filename')
s.send('data')
Can be received as:
s.recv(1024)
# 'put filenamedata'
So buffer data received and only extract full messages. One way is to send the size of a message before the message.

TCP Client retrieving no data from the server

I am trying to receive data from a TCP Server in python. I try to open a file at the server and after reading its content, try to send it to the TCP Client. The data is read correctly from the file as I try to print it first on the server side but nothing is received at the Client side.
PS. I am a beginner in network programming.
Server.py
import socket
import os
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 5000))
server_socket.listen(5)
client_socket, address = server_socket.accept()
print ("Conencted to - ",address,"\n")
data = client_socket.recv(1024).decode()
print ("Filename : ",data)
fp = open(data,'r')
string = fp.read()
fp.close()
print(string)
size = os.path.getsize(data)
size = str(size)
client_socket.send(size.encode())
client_socket.send(string.encode())
client_socket.close()
Client.py
import socket,os
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("", 5000))
size = 1024
print ("Your filename : \n")
string = input()
client_socket.send(string.encode())
size = client_socket.recv(1024).decode()
print ("The file size is - ",size[0:2]," bytes")
size = int(size[0:2])
string = client_socket.recv(size).decode()
print ("\nFile contains : ")
print (string)
client_socket.close();
Try:
#Get just the two bytes indicating the content length - client_socket.send(size.encode())
buffer = client_socket.recv(2)
size = len(buffer)
print size
print ("The file size is - ",buffer[0:2]," bytes")
#Now get the remaining. The actual content
print buffer.decode()
buffer = client_socket.recv(1024)
size = len(buffer)
print size
print buffer.decode()
Add Accept() in while loop as below.
while True:
client_socket, address = server_socket.accept()
print ("Conencted to - ",address,"\n")
......

Python Client Server program gets stucked

Server Code
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("192.168.169.10", 9559))
server_socket.listen(5)
import os
import time
client_socket, address = server_socket.accept()
print "Conencted to - ",address,"\n"
while(1):
fp = open('img.jpg','wb+')
start = time.time()
while True:
strng = client_socket.recv(1024)
if not strng:
break
print 'loop ends'
fp.write(strng)
fp.close()
print 'total time taken',time.time()-start,'secs'
print "Data Received successfully"
client_socket.send("Hey I am looking for you face")
exit()
Client Code
import socket,os
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("192.168.169.10", 9559))
fname = '/home/student/images/andrew1.jpeg'
img = open(fname,'rb')
while True:
strng = img.readline(1024)
if not strng:
break
client_socket.send(strng)
img.close()
response = client_socket.recv(1024)
print response
exit()
The Code gets stucked and when on the client side ctrl +C is pressed the server exits and the client doesnt receive data
How to achieve two way communication in this scenario ??

How to make the server side socket code run continuously

I have a server/client socket program that is used to transfer a file from the client to the server. The issue is that the code stops running once the file is transferred. I want to change it such that the server side code is continuously running so that I can transfer a file multiple times without having to run the code again and again
Server code:
import socket
host = ''
port = 5560
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created.")
try:
s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind comlete.")
return s
def setupConnection():
s.listen(1) # Allows one connection at a time.
conn, address = s.accept()
print("Connected to: " + address[0] + ":" + str(address[1]))
return conn
def storeFile(filePath):
picFile = open(filePath, 'wb')
print(filePath)
print("Opened the file.")
pic = conn.recv(1024)
#print(pic)
while pic:
print("Receiving picture still.")
picFile.write(pic)
pic = conn.recv(1024)
picFile.close()
def dataTransfer(conn):
# A big loop that sends/receives data until told not to.
while True:
# Receive the data
data = conn.recv(1024) # receive the data
data = data.decode('utf-8')
# Split the data such that you separate the command
# from the rest of the data.
dataMessage = data.split(' ', 1)
command = dataMessage[0]
if command == 'GET':
reply = GET()
elif command == 'REPEAT':
reply = REPEAT(dataMessage)
elif command == 'STORE':
print("Store command received. Time to save a picture")
storeFile(dataMessage[1])
reply = "File stored."
elif command == 'LED_ON':
callLED()
reply = 'LED was on'
else:
reply = 'Unknown Command'
# Send the reply back to the client
conn.sendall(str.encode(reply))
#print("Data has been sent!")
conn.close()
s = setupServer()
while True:
try:
conn = setupConnection()
dataTransfer(conn)
except:
break
The client side code is below:
import socket
from time import sleep
from time import time
host = '192.168.0.17'
port = 5560
data = "hi"
filepath = "/var/www/html/unknown.txt"
def setupSocket():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
return s
def sendPic(s, filePath):
print(filePath)
pic = open(filePath, 'rb')
chunk = pic.read(1024)
s.send(str.encode("STORE " + filePath))
t = time()
while chunk:
print("Sending Picture")
s.send(chunk)
#print(chunk)
chunk = pic.read(1024)
pic.close()
print("Done sending")
print("Elapsed time = " + str(time() - t) + 's')
#s.close()
return "Done sending"
def sendReceive(s, message):
s.send(str.encode(message))
reply = s.recv(1024)
print("We have received a reply")
print("Send closing message.")
s.send(str.encode("EXIT"))
#s.close()
reply = reply.decode('utf-8')
return reply
def transmit(message):
s = setupSocket()
response = sendReceive(s, message)
return response
def backup(filePath):
s = setupSocket()
response = sendPic(s, filePath)
return response
while True:
backup(filepath)
print("Backup Complete!")
break
I do not own the code. I have made some change to the code that I got from a YouTube video.
Have you had a look at the SocketServer module?
You could setup your dataTransfer() function as the handle() method of a RequestHandler class, then start your server with the serve_forever() method.

Categories