脚本中使用XOR解密功能失效问题求助
Hey there! I get it, hitting a bottleneck right at the finish line of an assignment is super frustrating. Let's work through this server automation task step by step, fixing and completing the code you've started, while keeping your "non-standard but acceptable" data reception approach intact.
1. 补全基础代码与导入
First, let's fix the truncated import and add core configuration. I'll assume your xor module has an encryption function like xor_encrypt (adjust if your actual function name differs):
# -*- encoding: utf-8 -*- import socket import sys import time from decryptmsg import decryptmsg from cleanmsg import cleanmsg from getkey import getkey from xor import xor_encrypt # 补全截断的导入语句
2. 稳定的服务器连接逻辑
Let's add a robust connection function that handles common errors:
def connect_to_server(host, port): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) print("✅ Connected to server successfully!") return sock except ConnectionRefusedError: print("❌ Server refused connection. Double-check host/port.") sys.exit(1) except Exception as e: print(f"❌ Connection failed: {str(e)}") sys.exit(1)
3. 数据接收(兼容你的需求)
You mentioned your current reception implementation is non-standard but works for the task. Here's a cleaned-up version of that approach, plus a standard alternative if you need it later:
简易接收版本(符合你的任务要求)
def receive_message(sock, buffer_size=1024): try: raw_msg = sock.recv(buffer_size) if not raw_msg: print("⚠️ Server closed the connection.") sock.close() sys.exit(1) return raw_msg except Exception as e: print(f"❌ Receive error: {str(e)}") sock.close() sys.exit(1)
规范接收版本(用于扩展场景)
If you ever need to handle longer messages without truncation:
def receive_message_standard(sock): # Receives full message using newline as delimiter full_msg = b"" while True: chunk = sock.recv(1024) if not chunk: break full_msg += chunk if b"\n" in chunk: break return full_msg.strip()
4. 核心消息处理流程(解密→清理→加密→回发)
This is likely where your bottleneck lies—let's make sure each step's input/output formats match (critical for encryption/decryption):
def process_and_send(sock): # Fetch encryption key (assumes getkey() returns a bytes object) key = getkey() if not key: print("❌ Failed to retrieve encryption key.") sock.close() sys.exit(1) print(f"🔑 Using encryption key: {key}\n") while True: # Step 1: Receive raw message from server raw_msg = receive_message(sock) print(f"📥 Received raw message: {raw_msg}") # Step 2: Decrypt the message # Adjust parameters if your decryptmsg expects different inputs (e.g., string instead of bytes) decrypted_msg = decryptmsg(raw_msg, key) print(f"🔓 Decrypted message: {decrypted_msg}") # Step 3: Clean the message (remove invalid chars, format, etc.) cleaned_msg = cleanmsg(decrypted_msg) print(f"🧹 Cleaned message: {cleaned_msg}") # Step 4: Encrypt and send back to server # Ensure we send bytes (convert string to bytes if needed) encrypted_response = xor_encrypt(cleaned_msg, key) send_data = encrypted_response.encode("utf-8") if isinstance(encrypted_response, str) else encrypted_response sock.sendall(send_data) print("📤 Response sent to server.\n") # Optional: Add small delay to avoid overwhelming the server time.sleep(1)
5. 主程序入口
Tie everything together with a main function:
if __name__ == "__main__": # Replace with your actual server host and port SERVER_HOST = "your-server-ip-or-domain" SERVER_PORT = 12345 server_socket = connect_to_server(SERVER_HOST, SERVER_PORT) try: process_and_send(server_socket) except KeyboardInterrupt: print("\n👋 Exiting program gracefully.") server_socket.close() sys.exit(0)
常见 Bottleneck Fixes
If you're still stuck, check these common issues:
- Mismatched data types: Ensure
decryptmsgaccepts bytes (sincerecvreturns bytes) andxor_encryptoutputs bytes for sending. - Key consistency: Verify
getkey()returns the exact same key used by the server (length and value). - Truncated messages: If your server sends messages longer than 1024 bytes, switch to the
receive_message_standardfunction. - Module imports: Confirm all your custom modules (
decryptmsg,cleanmsg, etc.) are in the same directory as your main script, and their function signatures match what you're calling.
内容的提问来源于stack exchange,提问作者Olli

