20181202 实验三《Python程序设计》实验报告
20181202 2019-2020-2 《Python程序设计》实验三报告
课程:《Python程序设计》
班级: 1812
姓名: 李祎铭
学号:20181202
实验教师:王志强
实验日期:2020年5月20日
必修/选修: 公选课
1.实验内容
创建服务端和客户端,服务端在特定端口监听多个客户请求。客户端和服务端通过Socket套接字(TCP/UDP)进行通信。
2. 实验过程及结果
构建service和client框架
# service
import socket
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8001))
s.listen()
conn, add = s.accept()
data = conn.recv(1024)
print(data.decode())
conn.sendall(("服务器已经收到了数据内容:"+str(data.decode())).encode())
s.close()
# client
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8001))
#str为文件内容
s.sendall(str.encode()) #需要编码
client端文件读取加密操作(RSA加密)
待发送文件和socket架构在同一目录
with open("./TCP/test.txt", 'rb') as fp:
data = fp.read()
key = open('./TCP/public.pem').read()
publickey = RSA.importKey(key)
# 进行加密
pk = PKCS1_v1_5.new(publickey)
encrypt_text = pk.encrypt(data)
# 加密通过base64进行编码
result = base64.b64encode(encrypt_text)
#print(result.decode())
service端消息解密写入文件(RSA解密)
data = str(data,'utf-8')
msg = base64.b64decode(data)
privatekey = open('./TCP/private.pem').read()
rsakey = RSA.importKey(privatekey)
# 进行解密
cipher = PKCS1_v1_5.new(rsakey)
text = cipher.decrypt(msg, 'DecryptError')
print(text.decode())
with open("./TCP/ser.txt" , "w") as fp:
fp.write(text.decode())
client端完整代码
import socket
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
# 客户端的socket初始化
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8001)) #以元组的形式连接
with open("./TCP/test.txt", 'rb') as fp:
data = fp.read()
key = open('./TCP/public.pem').read()
publickey = RSA.importKey(key)
# 进行加密
pk = PKCS1_v1_5.new(publickey)
encrypt_text = pk.encrypt(data)
# 加密通过base64进行编码
result = base64.b64encode(encrypt_text)
print(result.decode())
#
s.sendall(bytes(result.decode(),'utf-8')) #需要编码
#接收
data = s.recv(1024)
print(data.decode())
s.close
service端完整代码
import socket
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
# 服务端的socket初始化
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8001)) #绑定
s.listen() #监听
conn,address = s.accept()
data = conn.recv(2048)
data = str(data,'utf-8')
msg = base64.b64decode(data)
privatekey = open('./TCP/private.pem').read()
rsakey = RSA.importKey(privatekey)
# 进行解密
cipher = PKCS1_v1_5.new(rsakey)
text = cipher.decrypt(msg, 'DecryptError')
print(text.decode())
with open("./TCP/ser.txt" , "w") as fp:
fp.write(text.decode())
conn.sendall(("服务器已经收到了加密数据").encode())
# +str(data.decode())).encode()
s.close()
结果截图
client端
service端
产生的文件,test.txt为需要加密发送的文件,res.txt为解密写入的文件
3. 实验过程中遇到的问题和解决过程
- 问题1:socket技术的编码
- 问题1解决方案:必须在发送前转化为bytes类型,在接收时需要重新转化为str或其他类型
其他
码云链接:https://gitee.com/li_ming_XXL/to_learn_python/blob/master/TCP/socketTCPServer.py
https://gitee.com/li_ming_XXL/to_learn_python/blob/master/TCP/socketTCPclient.py