1 Star 0 Fork 0

hlzy/python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
clientf.py 1.83 KB
一键复制 编辑 原始数据 按行查看 历史
hlzy 提交于 2个月前 . 新增文件
# client.py
import socket
import os
from cryptography.fernet import Fernet
KEY = b'2DArf8mfLdgsDgwdnBQ5Uzr9zIRSEVerCnVk8Mn9xTQ='
BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("127.0.0.1", 8080))
cipher = Fernet(KEY)
def send_file(file_path):
try:
file_size = os.path.getsize(file_path)
file_name = os.path.basename(file_path)
# 发送文件头(加密)
header = f"FILE{SEPARATOR}{file_name}{SEPARATOR}{file_size}"
encrypted_header = cipher.encrypt(header.encode())
client_socket.send(encrypted_header)
# 分块发送文件内容
with open(file_path, "rb") as f:
while True:
bytes_read = f.read(BUFFER_SIZE)
if not bytes_read:
break
encrypted_data = cipher.encrypt(bytes_read)
client_socket.send(encrypted_data)
print(f"文件 {file_name} 发送完成")
except Exception as e:
print(f"文件发送失败: {str(e)}")
while True:
message = input("输入消息(/sendfile 发送文件):")
if message.startswith("/sendfile"):
_, file_path = message.split(" ", 1)
if os.path.exists(file_path):
send_file(file_path)
else:
print("文件不存在")
continue
# 普通消息处理
encrypted_msg = cipher.encrypt(message.encode("utf-8"))
client_socket.send(encrypted_msg)
if message == "exit":
break
# 接收回复
encrypted_data = client_socket.recv(BUFFER_SIZE)
try:
decrypted_data = cipher.decrypt(encrypted_data).decode("utf-8")
print(f"服务器回复:{decrypted_data}")
except:
print("解密失败!连接已终止")
break
client_socket.close()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/hlzy2004/python.git
git@gitee.com:hlzy2004/python.git
hlzy2004
python
python
master

搜索帮助