Files
p2pchat/app.py
T
2025-08-01 21:12:36 +08:00

56 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# cli/app.py
import os
from core.encryption import RSAEncryptor
from core.transport import UDPTransport
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FRIEND_PUBLIC_KEY_PATH = os.path.join(BASE_DIR,"ipchat", "config", "keys", "send", "public.key")
MY_PRIVATE_KEY_PATH = os.path.join(BASE_DIR,"ipchat", "config", "keys", "user", "private.pem")
MY_PUBLIC_KEY_PATH = os.path.join(BASE_DIR,"ipchat", "config", "keys", "user", "public.pem")
class P2PChatApp:
def __init__(self, friend_public_key_path: str, my_private_key_path: str, my_public_key_path: str):
self.encryptor = RSAEncryptor(friend_public_key_path, my_private_key_path, my_public_key_path)
def send_mode(self, target_ip: str, target_port: int):
transport = UDPTransport()
print(f"\n[>] 已连接到 {target_ip}:{target_port},输入消息内容直接发送(输入'q'退出)")
while True:
message = input(">>> ").strip()
if message.lower() in ('q', 'exit'):
print("[>] 退出发送模式")
break
if not message:
continue
try:
ciphertext = self.encryptor.encrypt(message)
transport.send(ciphertext, target_ip, target_port)
print(f"[√] 消息已发送")
except ValueError as e:
print(f"[!] 加密失败:{e}")
except Exception as e:
print(f"[!] 发送失败:{e}")
transport.close()
def listen_mode(self, listen_port: int):
print(f"[~] 正在监听 UDP 端口 {listen_port}(IPv4/IPv6 双栈支持)")
transport = UDPTransport(bind_port=listen_port)
while True:
data, sender_ip, sender_port = transport.receive()
if not data:
continue
try:
message = self.encryptor.decrypt(data)
print(f"\n[<] 来自 {sender_ip}:{sender_port} 的消息:{message}")
print(">>> ", end="", flush=True) # 保持输入提示符
except Exception as e:
print(f"\n[!] 解密失败:{e}")
print(">>> ", end="", flush=True)