0

I'm working on a screen Logger for a school project and for now I just send the screenshot from the client to the server, but in the server if I receive the size, I don't get the full file size.

I also tried to put the size I received from the client to check if it's the right size - and it is.

server code:

import os
import time
from datetime import datetime
import MySQLdb as mysql
import pygame
import socket


def server_setup():
    S_socket = socket.socket()
    print("Server is up and running")
    return S_socket


def client_blind():
    global server_socket
    print("turning on server")
    server_socket.bind(("0.0.0.0", 8820))
    server_socket.listen(1)
    (client_socket, client_address) = server_socket.accept()
    print(client_address[0])
    return client_socket, client_address


server_socket = server_setup()
client_socket, client_address = client_blind()

image_name = f"screenshot-{str(datetime.now())}"
image_name = image_name.replace(":", ";")
filepath = f"./screenshots/{image_name}.png"

size = int(client_socket.recv(10).decode())
print(size)
b = client_socket.recv(size)
print("message received")
with open(filepath, 'xb') as new_file:
    new_file.write(b)

client_socket.close()
server_socket.close()

client code:

import os
from datetime import datetime

import pygame
import pyscreenshot as ImageGrab
import socket


def take_screenshot():
    print("Taking screenshot...")

    image_name = f"screenshot-{str(datetime.now())}"
    image_name = image_name.replace(":", ";")
    screenshot = ImageGrab.grab(backend="mss", childprocess=False)

    filepath = f"./screenshots/{image_name}.png"

    screenshot.save(filepath)

    file = open(filepath, 'rb')
    b = file.read()
    file.close()
    os.remove(filepath)

    return b


def main():
    my_socket = socket.socket()
    my_socket.connect(("127.0.0.1", 8820))

    clock = pygame.time.Clock()
    file = take_screenshot()
    print(str(len(str(file))))
    my_socket.send(str(len(str(file))).zfill(10).encode()+file)
    # while True:
    # take_screenshot()
    # clock.tick(20)

    my_socket.close()

if __name__ == '__main__':
    main()

I'm pretty sure the problem is in the server code, but not 100% sure

  • 1
    In short: you are assuming that `send` will actually sent everything given and `recv` will receive all data based on the size given. Both assumptions are wrong. `send` can send less then provided and `recv` can receive less then asked for - you need to check the return values. – Steffen Ullrich Nov 21 '22 at 12:49
  • but if I remove the the size = int(client_socket.recv(10).decode()) it works perfectly fine – Matan F Nov 21 '22 at 18:50
  • If you remove this line then `size` is not defined, so you cannot call `recv(size)`. – Steffen Ullrich Nov 21 '22 at 18:59
  • I meant that if I removed size and changed it to ```b = client_socket.recv(595802)``` it works – Matan F Dec 05 '22 at 11:22

0 Answers0