I'm new to python and i can't figure out what's wrong with my code here :
I set up a client and a server (both on localhost) , the server take a snapshot and suppose to send it to the client which saves it in some folder , it's all happening , but the JPG file doesn't open the picture correctly , instead it's says that it doesn't support the file format :\
the code:
clientFile.py
import socket
# set up a socket connection object
my_socket = socket.socket()
# make the socket connect to a certain ip&port
my_socket.connect(("127.0.0.1", 8821))
data = ''
while data != 'EXIT':
message = input('enter a message to send to the server \n')
# send the server what to do (in this case take a snapshot)
my_socket.send(message.encode())
data = my_socket.recv(1024).decode()
if data == 'snapshot has been taken':
# recieve the file's byte length from the server ( for example: 2000000 bytes => 7 length)
data = my_socket.recv(1).decode()
sizeLength = int(data) % 10
# recieve the size of the file picture
data = my_socket.recv(sizeLength).decode()
size = int(data)
# recieve the file in binary
picture = my_socket.recv(size)
# trying to write the file :\
myfile = open(r'C:\test\client\screen.jpg', 'wb')
myfile.write(picture)
myfile.close()
else:
print('closing the socket')
my_socket.close()
server.py
import socket
import datetime
import glob
import os
import pyautogui
import subprocess
server_socket = socket.socket()
# accepting a socket from which client (0.0.0.0) means everyone
server_socket.bind(("0.0.0.0", 8821))
server_socket.listen()
# accept sockets and recieve socket and client ip&port as tuples
(client_socket, client_address) = server_socket.accept()
# data = client_socket.recv(1024).decode()
data = ''
while data != 'EXIT':
.
.
.
elif data == 'SNAPSHOT':
#snapshot saved succesfully !
image = pyautogui.screenshot()
image.save(r'C:\test\screen.jpg')
# file stats (size and stuff)
picStats = os.stat(r'C:\test\screen.jpg')
picSize = picStats.st_size
picLength = len(str(picSize))
myfile = open(r'C:\test\screen.jpg', 'rb')
print(myfile.read())
reply = 'snapshot has been taken'
# make the client prepere for the picture to be send
client_socket.send(reply.encode())
# send the picture length
client_socket.send(str(picLength).encode())
# send the picture size
client_socket.send(str(picSize).encode())
client_socket.send(myfile.read())
.
.
.
#closing sockets eventually ...
i think i'm missing something here... thanks
Well I have one issue with the code:
# This reads all the bytes in the file
print(myfile.read())
# this will read nothing since the file cursor is already at the end of the file.
client_socket.send(myfile.read())
Either set the bytes to an internal object file_bytes= myfile.read()
or reset the cursor between reads myfile.seek(0)