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

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

服务器:

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()           

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

 

posted @ 2019-07-19 22:28  浪上了天  阅读(908)  评论(1编辑  收藏  举报