python note 26 socket

1、server

import socket
sock = socket.socket()
sock.bind(('127.0.0.1',8000))
sock.listen(5)

while 1:
    conn,addr = sock.accept()
    while 1:
        try:
            data = conn.recv(1024).decode("utf-8")
            user,pwd = data.strip().split("|")

            flag = False
            with open("account","r") as f:
                for line in f:
                    print(line.strip().split(":"))
                    username,password = line.strip().split(":")
                    if username == user and password == pwd :
                        flag = True
                        break

            if flag:
                conn.send(b"success")
            else:
                conn.send(b"fail")
        except Exception as e:
            break

2、client

import socket
sock = socket.socket()
sock.connect(('127.0.0.1',8000))

while 1:
    user = input('用户名>>>')
    pwd = input('密码>>>')
    val = ("%s|%s" %(user,pwd)).encode("utf-8")
    sock.send(val)
    res = sock.recv(1024)
    print(res.decode("utf-8"))
    if res.decode("utf-8") == "success":
        break
    else:
        continue

 

posted @ 2019-07-05 15:55  P-Z-W  阅读(106)  评论(0)    收藏  举报