Python Socket Communication разрывается при удалении оператора печатиPython

Программы на Python
Anonymous
 Python Socket Communication разрывается при удалении оператора печати

Сообщение Anonymous »

Я отправляю многострочную строку Python с сокетом: < /p>
elif command=="help":
help_options='''
download
-> Download a File from Target Machine
upload -> Upload a File to Targe
get -> Download a File to Target Machine from Internet
start -> Start Program on Target Machine
screenshot -> Take screenshot of the Target Screen
check -> Check for Administrator Privileges
'''
lines=help_options.splitlines()
for line in lines:
send_payload(line.encode("utf-8"))
send_payload("END".encode("utf-8"))
< /code>
от клиента это то, как я получаю: < /p>
elif command=="help":
complete_message=""
while True:
line=receive_payload()
# ---- FIRST TRY FAILED
# if not line:
# time.sleep(0.01)
# continue

# --- SECOND TRY FAILED
# if not line:
# continue

# --- THIRD TRY FAILED ---
# time.sleep(0.01)

# ------- IT WORKS ONLY WITH THIS PRINT STATEMENT
# print(f"line {line}")
if line=="END":
break
if isinstance(line,bytes):
complete_message += line.decode('utf-8') + "\n"
else:
complete_message+=line+"\n"
print(complete_message)
< /code>
Я успешно получил текст по ошибке, когда добавил эту строку отладки < /p>
print(f"line {line}")


Кто -нибудь знает, почему цикл работает только при печати полученных данных? Что -то происходит с буфером сокета или способом обработки данных в кусках? >receive_payload и send_payload Функции успешно работают. При необходимости я могу опубликовать < /p>
Это send_payload < /p>
def send_payload(data):
if isinstance(data, bytes):
# If data is in binary form (like a file), encode it in base64
data = base64.b64encode(data).decode('utf-8')
padding = len(data) % 4
if padding != 0:
data += "=" * (4 - padding) # Manually add padding if necessary

# By converting the entire data object to a JSON string, the function ensures that all data is sent as a single, self-contained message.
# This reduces the risk of partial or malformed messages due to network issues or incorrect handling of the raw data.
json_data = json.dumps({"data": data}) # Package the data in a dictionary and then serialize it
sock.send(json_data.encode("utf-8"))

print("data is sent from target machine")

Это recee_payload :
def receive_payload():
json_data = ""
while True:
try:
chunk = target.recv(1024).decode("utf-8")
print(f"Chunk received: {chunk}")
if not chunk:
print("No chunk received")
break
json_data += chunk # Collect chunks
try:
data = json.loads(json_data) # Load JSON data
file_data = data.get("data")
if file_data:
# Ensure correct padding for base64 data
padding = len(file_data) % 4
if padding != 0:
print(f"Adding {4 - padding} padding to base64 data.")
file_data += "=" * (4 - padding)
# Decode the base64 data
file_data = base64.b64decode(file_data)
return file_data # Return decoded data
except base64.binascii.Error as e:
print(f"Error during base64 decoding: {e}")
pass
return None # If it's not base64-encoded, return None
except json.JSONDecodeError:
# Handle incomplete JSON
print("Incomplete JSON received. Waiting for more data.")
continue


Подробнее здесь: https://stackoverflow.com/questions/793 ... -statement

Вернуться в «Python»