python_remote_access/Controller/controller-screen.py

62 lines
1.8 KiB
Python
Raw Permalink Normal View History

2021-04-19 14:37:54 +01:00
import socket
import os
#from test import update_image
# device's IP address
SERVER_HOST = "0.0.0.0" #(socket.gethostbyname(socket.gethostname()))
SERVER_PORT = 5002
# receive 4096 bytes each time
BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"
# create the server socket
# TCP socket
2021-04-19 14:46:23 +01:00
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2021-04-19 14:37:54 +01:00
# bind the socket to our local address
s.bind((SERVER_HOST, SERVER_PORT))
# enabling our server to accept connections
# 5 here is the number of unaccepted connections that
# the system will allow before refusing new connections
2021-04-19 15:14:44 +01:00
# s.listen(5)
2021-04-19 14:37:54 +01:00
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
# accept connection if there is any
2021-04-19 15:14:44 +01:00
# client_socket, address = s.accept()
2021-04-19 14:37:54 +01:00
# if below code is executed, that means the sender is connected
2021-04-19 15:14:44 +01:00
# print(f"[+] {address} is connected.")
2021-04-19 14:37:54 +01:00
# receive the file infos
# receive using client socket, not server socket
2021-04-19 15:14:44 +01:00
received = s.recv(BUFFER_SIZE).decode()
2021-04-19 14:37:54 +01:00
filename, filesize = received.split(SEPARATOR)
# remove absolute path if there is
#filename = os.path.basename(filename)
# convert to integer
filesize = int(filesize)
# start receiving the file from the socket
# and writing to the file stream
#with open(filename, "wb") as f:
while True:
# read 1024 bytes from the socket (receive)
2021-04-19 15:14:44 +01:00
bytes_read = s.recv(BUFFER_SIZE)
2021-04-19 14:37:54 +01:00
if not bytes_read:
# nothing is received
# file transmitting is done take another time
break
# write to the file the bytes we just received
try:
hello = bytes_read.decode()
#update_image()
os.remove("screen.jpg")
os.rename(r"screen_download.jpg",r"screen.jpg")
print("I am moving the file")
except:
f = open("screen_download.jpg", 'ab')
f.write(bytes_read)
print("I am adding to the file")
f.close()
# close the client socket
#client_socket.close()
# close the server socket
#s.close()