注册.py
import hashlib
def register(username, password):
with open('info', 'a+', encoding='utf-8') as f:
f.write(username + '|' + password + '\n')
username = input('请输入用户名>>>')
password = input('请输入密码>>>')
md5_obj = hashlib.md5(password.encode('utf-8'))
# 要对哪个字符串进行加密,就放这里
md5_obj.update(username.encode('utf-8'))
# 拿到加密字符串
pawd_m = md5_obj.hexdigest()
md5_obj = hashlib.md5(b'12345678')
md5_obj.update(pawd_m.encode('utf-8'))
# 拿到加密字符串
pawd_m = md5_obj.hexdigest()
register(username, pawd_m)
server.py
import socketserver
import pickle
import hashlib
# 让一个服务器接收多个客户端
class MySocket(socketserver.BaseRequestHandler):
# 固定名字
def handle(self):
# 收发的逻辑代码
# self.request = conn
# self.request.send()
# self.request.recv()
while 1:
pic_dic = self.request.recv(1024)
# 处理空消息
if not pic_dic:
break
dic = pickle.loads(pic_dic)
if not dic['status']:
# 登陆失败
with open('info', 'r', encoding='utf-8') as f:
flag = 0
for info in f:
username, pawd_txt = info.strip().split('|')
# 用户存在
if username == dic['username']:
flag = 1
md5_obj = hashlib.md5(b'12345678')
md5_obj.update(dic['password'].encode('utf-8'))
pawd_m = md5_obj.hexdigest()
if pawd_m == pawd_txt:
dic['status'] = True
break
else:
dic['reason'] = '密码错误'
if not flag:
dic['reason'] = '用户不存在'
pic_dic = pickle.dumps(dic)
self.request.send(pic_dic)
else:
# 登陆成功
pass
# 固定写法
server = socketserver.TCPServer(('192.168.1.107', 18080), MySocket)
# 开启一个永久性的服务
server.serve_forever()
client.py
import socket
import hashlib
import pickle
client = socket.socket()
client.connect(('192.168.1.107', 18080))
# 服务器应该回复一个字典:是否登陆成功;如果没有登陆成功是因为什么原因
c = 3
while c:
dic = {'status': False, 'username': None, 'password': None}
username = input('请输入用户名>>>')
password = input('请输入密码>>>')
md5_obj = hashlib.md5(password.encode('utf-8'))
# 要对哪个字符串进行加密,就放这里
md5_obj.update(username.encode('utf-8'))
# 拿到加密字符串
pawd_m = md5_obj.hexdigest()
dic['username'] = username
dic['password'] = pawd_m
pic_dic = pickle.dumps(dic)
client.send(pic_dic)
pic_dic = client.recv(1024)
dic = pickle.loads(pic_dic)
if dic['status']:
print('登陆成功')
break
else:
print(dic['reason'])
c -= 1
client.close()