标签:block 报错 encode inf nbsp TE dom 登陆验证 启动服务
server: import socketserver import json class MyServer(socketserver.BaseRequestHandler): def handle(self): str_dic = self.request.recv(1024).decode(‘utf-8‘) dic = json.loads(str_dic) with open(‘user_info‘,encoding=‘utf-8‘) as f: for line in f: name,psw = line.strip().split(‘|‘) if name == dic[‘username‘] and psw == dic[‘password_md5‘]: print(‘登陆成功‘) return print(‘用户名或密码错误‘) ser = socketserver.ThreadingTCPServer((‘127.0.0.1‘,8090),MyServer) ser.serve_forever() client: import socket import json import hashlib sk = socket.socket() sk.connect(((‘127.0.0.1‘,8090))) username = input(‘请输入用户名‘).strip() password = input(‘请输入密码‘).strip() obj = hashlib.md5() obj.update(password.encode(‘utf-8‘)) password_md5 = obj.hexdigest() dic = {‘username‘:username,‘password_md5‘:password_md5} str_dic = json.dumps(dic) sk.send(str_dic.encode(‘utf-8‘)) sk.close()
server: import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self): self.request.send(b‘hello‘) print(self.request.recv(1024)) #协议及地址,类名 ser = socketserver.ThreadingTCPServer((‘127.0.0.1‘,8081),MyServer) #启动服务 ser.serve_forever()#永远的开启服务。 client: import socket sk = socket.socket() sk.connect((‘127.0.0.1‘,8081)) print(sk.recv(1024)) sk.send(b‘hello‘) sk.close()
server: import socket import hashlib import os def create_sock(): sk = socket.socket() sk.bind((‘127.0.0.1‘,8080)) sk.listen(5) conn , addr = sk.accept() return conn,sk def com(conn): while 1: msg_r = conn.recv(1024).decode(‘utf-8‘) print(msg_r) msg_s = input(‘>>>‘) conn.send(msg_s.encode(‘utf-8‘)) def md5_confir(conn): salt = b‘fuck‘ md5_bytes = os.urandom(10) obj = hashlib.md5(salt) obj.update(md5_bytes) r = obj.hexdigest() conn.send(md5_bytes) r_hex = conn.recv(1024).decode(‘utf-8‘) if r == r_hex: com(conn) else: print(‘非法客户端‘) conn , sk = create_sock() md5_confir(conn) conn.close() sk.close() client: import socket import hashlib def create_sk(): sk = socket.socket() sk.connect((‘127.0.0.1‘,8080)) return sk def com(sk): while 1: msg_s = input(‘>>>‘) sk.send(msg_s.encode(‘utf-8‘)) msg_r = sk.recv(1024).decode(‘utf-8‘) print(msg_r) def md5_conf(sk): salt = b‘fuck‘ md5_bytes = sk.recv(1024) obj = hashlib.md5(salt) obj.update(md5_bytes) r_hex = obj.hexdigest() sk.send(r_hex.encode(‘utf-8‘)) sk = create_sk() md5_conf(sk) com(sk) sk.close()
# socket中的一些常见方法 # import socket # # sk = socket.socket() # # sk.bind((‘127.0.0.1‘,8090)) # # sk.setblocking(False)#默认为真,设置为假当accept时不阻塞。如果没有客户端连接则报错。 # sk.settimeout(2) #设置隔几秒后还没有客户端连接时报错。 # # sk.listen(5) # conn , addr = sk.accept() # # print(conn.getsockname()) #得到服务器的ip+port # print(conn.getpeername()) #得到客户端的ip+port # # # conn.close() # sk.close() #验证是否为合法的客户端。 #socketserver
标签:block 报错 encode inf nbsp TE dom 登陆验证 启动服务
原文地址:https://www.cnblogs.com/liujjpeipei/p/9152543.html