其他分享
首页 > 其他分享> > 网络通信远程操控

网络通信远程操控

作者:互联网

客户端

import socket
def login():
    print('=========欢迎使用登入功能=========')
    name = input('输入账号:').strip()
    pwd = input('输入密码:').strip()
    return name,pwd

def register():
    while True:
        print('=========欢迎使用注册功能=========')
        name = input('输入账号:').strip()
        pwd = input('输入密码:').strip()
        re_pwd = input('再次输入密码').strip()
        if pwd == re_pwd:
            return name,pwd
        else:
            print('两次输入的密码不同')




client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(('127.0.0.1',8080))

dic = {
    '0':login,
    '1':register
}

while True:
    print('''
    0:登入
    1:注册
    2:退出
    ''')
    cmd = input('输入功能编号:').strip()
    if cmd == '2':
        break
    if cmd not in dic:
        print('请输入正确的编号')
        continue
    username,password = dic[cmd]()
    str = cmd+' '+username+' '+password
    # print(str)
    client.send(str.encode('utf-8'))
    date = client.recv(1024)
    print(date.decode('utf-8'))
client.close()

服务端

import os
import socket
base_path = os.path.dirname(__file__)
def register_interface(username,password):
    path = os.path.join(base_path,username+'txt')
    if not os.path.exists(path):
        with open(path,'wt',encoding='utf-8') as f:
            f.write(f'{username} {password}')
        return True,'注册成功'
    return False,'已有该用户'

def login_interface(username,password):
    path = os.path.join(base_path, username+'txt')
    if not os.path.exists(path):
        return False,'用户不存在'
    with open(path,'r',encoding='utf-8')as f:
            name,pwd = f.read().split(' ')
    if pwd == password:
        return True,'登入成功'




server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(('127.0.0.1',8080))
server.listen(5)
while True:
    print('等待连接......')
    conn,client_addr= server.accept()
    print('连接成功,客户端的ip和端口为:',client_addr)
    while True:
        try:
            cmd,username,password = conn.recv(1024).decode('utf-8').split(' ')
            if cmd == '1':
                flag,msg = register_interface(username,password)
                conn.send(msg.encode('utf-8'))elif cmd == '0':
                flag, msg = login_interface(username, password)
                conn.send(msg.encode('utf-8'))
        except Exception:
            break
    conn.close()

 

标签:网络通信,username,操控,socket,pwd,print,path,password,远程
来源: https://www.cnblogs.com/bk134/p/12739984.html