20231325 贾罗祁 实验三《Python程序设计》实验报告

20231325贾罗祁 2023-2024-2《Python程序设计》实验三报告

课程:《Python程序设计》
班级: 2313
姓名: 贾罗祁
学号: 20231325
实验教师:王志强
实验日期:2024年4月17日
必修/选修: 公选课

1.实验内容

  • 创建服务端和客户端,服务端在特定端口监听多个客户请求。
    客户端和服务端通过Socket套接字(TCP/UDP)进行通信。

2.实验过程及结果

1.代码:
1.创建服务端

(1)DesModule:
from pyDes import *
import binascii
def des_encrypt(s, KEY):
secret_key = KEY
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
en = k.encrypt(s, padmode=PAD_PKCS5)
return binascii.b2a_hex(en).decode()
def des_descrypt(s, KEY):
secret_key = KEY
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
return de.decode()
if name == "main":
ciphertext = des_encrypt("hello, world!", "12345678")
print("密文:",ciphertext)
plaintext = des_descrypt(ciphertext, "12345678")
print("解密后的明文:", plaintext)
(2)SocketServer:
import socket
from DesModule import des_descrypt,des_encrypt
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("192.168.234.244", 5418))# s.bind("localhost") 0-65535
s.listen()
conn, address = s.accept()#阻塞
data = conn.recv(1024)#接收
print("从客户端收到的信息为:", data.decode())
conn.sendall("长江长江,我是黄河,信息已收到!".encode())

s.close()
(3)SocketServerforever:
import socket

tcpserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpserver.bind(("192.168.234.244", 5418))
tcpserver.listen(5)
while True:
conn, addr = tcpserver.accept()
print(conn)
while True:
try:
data = conn.recv(1024)
print(data.decode("utf-8"))
# ret_data = "收到!"
ret_data = input("请回复:")
conn.send(ret_data.encode('utf-8'))
except Exception:
break
conn.close()

2.创建客户端

(1)SocketClient:
import socket
import os
from DesModule import *
file1 = open("秘密", "r+")#"w"
file1.write("黄河!黄河!你吃了吗?")
file1.seek(0)
cryptostring = file1.readline()
print(cryptostring)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("192.168.234.244", 5418))
s.connect(("192.168.43.158", 6000))
s.sendall(cryptostring.encode())
data = s.recv(1024)
print("从服务器接收的数据为:",data.decode())
s.close()
(2)SocketClientforever:
import socket

tcpclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpclient.connect(("192.168.234.244", 5418))
while True:
while True:
data = input('>>>').strip()
tcpclient.send(data.encode('utf-8'))
ret = tcpclient.recv(1024)
print(ret.decode('utf-8'))
tcpclient.close()

2.运行结果:

(1)作为服务端:
1
(2)作为客户端:
2

3.实验过程中遇到的问题和解决过程

问题一:我连接不上合作的同学
问题一解决方案:要注意端口一致,同时确保ip应为电脑ip地址

posted @ 2024-04-23 23:16  20231325贾罗祁  阅读(14)  评论(0编辑  收藏  举报