Want to send image file using sockets in python - python

using a library called ImageGrab from PIL folder, i tryed to screenshot the server screen and send it to the customer. I saved the screenshot in a folder but how to send it? and if the image size is too big how do I split it and send it in pieces to the customer?
Server Side:
import socket
from PIL import ImageGrab
server_socket = socket.socket()
server_socket.bind('0.0.0.0', 8820)
server_socket.listen(1)
(client_socket, client_address) = server_socket.accept()
print client_address + ' Have connected to server'
commend = client_socket.recv(1024)
while commend != 'exit':
if commend == 'screenShot':
im = ImageGrab.grab()
im.save(r'C:\screen.jpg')
server_socket.close()
Client Side:
import socket
my_socket = socket.socket()
my_socket.connect('127.0.0.1', 8820)
commend = raw_input('Connected! Enter your commend')
my_socket.send(commend)
my_socket.close()
ty for help

Related

Unable to use sockets to send data over the internet in python

I am trying to write a script to transmit an image over the internet using sockets (the code is shown below). When I try it on the local machine the code works fine but when I do the same with 2 different computers (1 working as a server and 1 as client) connected to the same WiFi network, they don't even connect to one another let alone transmit data. Can anyone please help?
The server code :-
import socket
import base64
import sys
import pickle
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 8487))
s.listen(5)
while True:
# After the Connection is established
(clientsocket, address) = s.accept()
print(f"Connection form {address} has been established!")
# Initiate image conversion into a string
with open("t.jpeg", "rb") as imageFile:
string = base64.b64encode(imageFile.read())
msg = pickle.dumps(string)
print("Converted image to string")
# Send the converted string via socket encoding it in utf-8 format
clientsocket.send(msg)
clientsocket.close()
# Send a message that the string is sent
print("String sent")
sys.exit()
The client code :-
import socket, pickle, base64
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 8487))
while True:
data = []
# Recieve the message
while True:
packet = s.recv(1000000)
if not packet:
break
data.append(packet)
print("Message recieved")
# Decode the recieved message using pickle
print("Converting message to a String")
string = pickle.loads(b"".join(data))
print("Converted message to String")
# Convert the recieved message to image
imgdata = base64.b64decode(string)
filename = 'tu.jpeg'
with open(filename, 'wb') as f:
f.write(imgdata)
s.shutdown()
s.close()
s.connect((socket.gethostname(), 8487))
Your client attempts to connect to the local host. If the server host is the local host this works. But if the server host is different this will of course not connect to the server. Instead you have to provide the IP address or hostname of the servers system here.

Sockets return no data on virtualbox

I have a simple socket written in python to send a request to the server(Virtualbox Kali Linux) and receive some data from it. It seems like, it is connecting, but receiving no data. Screenshot of behaviour - https://prnt.sc/ragj7q
Here you can see a network config of the Virtualbox
Sever code:
import socket
def SocketMon():
serversocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serversocket.bind((socket.gethostname(),1234))
serversocket.listen(5)
while True:
clientsocket,address = serversocket.accept()
clientsocket.send(bytes("welcome"),"utf-8")
SocketMon()
Client code:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("127.0.0.1",1234))
msg = s.recv(1024)
print(msg.decode("utf-8"))

Pickle data was truncated (desktop streaming)

I'm trying to build a desktop streaming app. It consists of a server and a client for now. I learned that I should use the library pickle in order to serialize/deserialize the data. However, when I run both the scripts, I get the error "Pickle data was truncated" from the client side. Could you help me to solve this? I tried the solution the following link, whose OP apparently was trying to do the similar think but it didn't work.
python 3.6 socket pickle data was truncated
Server
import numpy as np
import cv2
from PIL import ImageGrab
import socket
import pickle
HOST = "0.0.0.0"
SOCKET = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST,SOCKET))
while True:
s.listen(5)
client, addres = s.accept()
print(addres, " has connected")
img = ImageGrab.grab()
img_np = np.array(img)
img_np_serial = pickle.dumps(img_np)
client.send(img_np_serial)
if cv2.waitKey(1) == 27:
break
cv2.destroyAllWindows()
Client
import socket
import pickle
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostbyname(socket.gethostname()),5000))
data = b""
while True:
packet = s.recv(4096)
if not packet: break
data += packet
data_deserial = pickle.loads(data)
print((data_deserial))

How do I send things that aren't strings with sockets? E.g taking a screenshot with the client and sending it to the server

My client's part of it
agreement_ac = s.recv(4096)
b = bytes("take a screenshot".encode())
if b in agreement_ac:
image = ImageGrab.grab()
My server's part:
while True:
c, addr = s.accept()
cmd_test = input(">>> ")
if cmd_test == "test":
c.send("take a screenshot".encode())
So currently what my application is doing is that when I start the server and a client connects, if I type in "take a screenshot" then that string will be sent to the client, the client will decode it to understand what it's supposed to do and then its gonna take a screenshot which it does and send it over. I don't understand how I can send it over to the server and save it on the server's device. E.g the client takes the screenshot and sends it to the server and the server saves it on the server's desktop.
Server code:
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))
s.listen(5)
print ("socket is listening")
while True:
c, addr = s.accept()
cmd_test = input(">>> ")
if cmd_test == "test":
c.send("take a screenshot".encode())
temp = c.recv(9000000)
with open('imgs.png','wb') as f:
#print(temp)
f.write(temp)
c.close()
client code:
import socket
import pyscreenshot as ImageGrab
b="take a screenshot"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12345
s.connect(('127.0.0.1', port))
#s.sendall(str.encode(b))
agreement_ac = str(s.recv(9000000))
#print(agreement_ac)
if b in agreement_ac:
image = ImageGrab.grab()
ImageGrab.grab_to_file('im.png')
with open('im.png','rb') as f:
imgsend = f.read()
s.sendall(imgsend)
#print(image)
s.close()
It will save the file on server pc as 'imgs.png'. Do change the byte size according to your need.
Accept if working :)

sending images from client to server using socket python

I'm trying to send multiple images from client to server .
from my client I send one image at a time then for each image I get the size in the server and then send the size back to client and then try and store all the sizes of all images in a table .
I wrote this code and it doesn't seem to work:
client.py:
from PIL import Image
import glob
import sys
import pickle
import socket
import os
import numpy
reload(sys)
def readFileImages(strFolderName):
st = os.path.join(strFolderName, "*.png")
print st
return glob.glob(st)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
client_socket.bind(("127.0.0.1", 4000))
list1=readFileImages("test")
myoutput =[]
while (list1):
for im in list1:
f=open(im,"rb")
while True:
veri = f.read()
if not veri:
break
client_socket.send(veri)
f.close()
data = client_socket.recv(4096)
data_arr=pickle.loads(data)
newrow=numpy.asarray(data_arr)
myoutput=numpy.vstack([myoutput,newrow])
client_socket.close()
numpy.savetxt("testTable.csv",myoutput,delimiter=",")
server.py:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1);
s.bind(("127.0.0.1",4000))
s.listen(5)
client_socket, address = s.accept()
print "Connected to - ",address,"\n"
fname="test.png"
fp = open(fname,'wb')
# image
while True:
strng = client_socket.recv(1024)
if not strng:
break
fp.write(strng)
fp.close()
#T[0]=detect_carte_grise(fp)
im = Image.open(fp)
T= im.size #width,height
data=pickle.dumps(T)
client_socket.send(data)
and why do i get this error ?:[errno98] address already in use
I cannot even connect to server
First, in server code you bind to port, but in client code, you need to CONNECT to that server. You are binding in both of your scripts and address is already used by the first running script. so in client drop bind and change to client_socket.connect(("127.0.0.1", 4000)). That will resolve current issues, if you have any more, please, ask another question.
I got the same error, I Changed the "port number". It's worked fine

Categories