码迷,mamicode.com
首页 > 编程语言 > 详细

Python socket编程 (2)--实现文件验证登入

时间:2019-07-19 23:51:02      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:color   port   encode   break   print   class   code   换行符   utf-8   

可以实现从客户端输入账号和密码然后发送到服务器进行验证,实现用户登入校正操作。

服务器:

import socket
import json
server = socket.socket()
server.bind((192.168.101.5, 8001))
server.listen(5)
while True:
    coon, addr = server.accept()
    while True:
        ret = coon.recv(1024)
        Info = json.loads(ret)
        """
        因为尝试了很多次,输入都是正确的,但是都是显示登入失败
        就想看看是不是哪里错,从这里打印看发现都是字符串
        没有类型错误,但是就是一直发登入失败,
        """
        # print(Info)
        # print(Info[‘name‘],type(Info[‘name‘]))
        # print(Info[‘password‘],type(Info[‘password‘]))
        flag = False
        with open(Info.txt, r) as f:
            for line in f:
                # lst = line.strip(‘:‘)        从这里打印后,发现从文件读取时,会把换行符读取进去
                # print(lst)                    所以要加上strip()函数
                name, passward = line.strip().split(:)
                # print(name,type(name))
                # print(passward,type(passward))
                if name == Info[name] and passward == Info[password]:
                    flag = True
                    break
            if flag:
                coon.send(登入成功.encode(utf-8))
            else:
                 coon.send(用户名或密码错误!.encode(utf-8))
    server.close()

客户端:

ort socket
import json
client = socket.socket()                       
client.connect((192.168.101.5, 8001))        
while True:
    while True:
        name = input(">>>请输入账号:")
        password = input(">>>请输入密码:")
        Info = json.dumps({name:name, password:password}).encode(utf-8)
        # print(Info)
        client.send(Info)                     
        ret = client.recv(1024)                
        print(ret.decode(utf-8))
    client.close()           

经过一番排查错误,总算是勉强实现了预期的功能。以后继续完善和添加新的功能!

 

Python socket编程 (2)--实现文件验证登入

标签:color   port   encode   break   print   class   code   换行符   utf-8   

原文地址:https://www.cnblogs.com/hxf-zb/p/11216049.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!