import socket
import threading
import json
import os

HOST = '0.0.0.0'
PORT = 65432
HOMEWORK_FILE = 'homework.txt'
SCORES_FILE = 'scores.json'

class Server:
    def __init__(self):
        self.homeworks = []
        self.scores = {}
        self.load_data()
        self.hw_lock = threading.Lock()
        self.scores_lock = threading.Lock()

    def load_data(self):
        if os.path.exists(HOMEWORK_FILE):
            with open(HOMEWORK_FILE, 'r') as f:
                self.homeworks = [line.strip() for line in f]
        
        if os.path.exists(SCORES_FILE):
            with open(SCORES_FILE, 'r') as f:
                self.scores = json.load(f)

    def save_homework(self):
        with open(HOMEWORK_FILE, 'w') as f:
            f.write('\n'.join(self.homeworks))

    def save_scores(self):
        with open(SCORES_FILE, 'w') as f:
            json.dump(self.scores, f)

    def authenticate(self, username, password):
        try:
            num = int(username)
            if 1 <= num <= 5:
                return password == 'admin123'
            elif 6 <= num <= 45:
                return password == '123456'
            return False
        except:
            return False

    def handle_admin(self, conn):
        conn.sendall(b'Admin Menu:\n1. Add homework\n2. Delete homework\n3. View scores\n4. Exit\n')
        while True:
            try:
                choice = conn.recv(1024).decode().strip()
                if choice == '1':
                    conn.sendall(b'Enter homework content: ')
                    hw = conn.recv(1024).decode().strip()
                    with self.hw_lock:
                        self.homeworks.append(hw)
                        self.save_homework()
                    conn.sendall(b'Homework added!\n')
                elif choice == '2':
                    with self.hw_lock:
                        if not self.homeworks:
                            conn.sendall(b'No homework to delete!\n')
                            continue
                        hw_list = '\n'.join([f'{i+1}. {h}' for i, h in enumerate(self.homeworks)])
                        conn.sendall(f'Current homeworks:\n{hw_list}\nEnter number to delete: '.encode())
                        num = conn.recv(1024).decode().strip()
                        try:
                            idx = int(num) - 1
                            if 0 <= idx < len(self.homeworks):
                                del self.homeworks[idx]
                                self.save_homework()
                                conn.sendall(b'Homework deleted!\n')
                            else:
                                conn.sendall(b'Invalid number!\n')
                        except:
                            conn.sendall(b'Invalid input!\n')
                elif choice == '3':
                    with self.scores_lock:
                        if not self.scores:
                            conn.sendall(b'No scores recorded!\n')
                        else:
                            res = ['Scores:']
                            for user, scores in self.scores.items():
                                res.append(f'{user}: {scores}')
                            conn.sendall('\n'.join(res).encode() + b'\n')
                elif choice == '4':
                    conn.sendall(b'Goodbye!\n')
                    break
                else:
                    conn.sendall(b'Invalid choice!\n')
            except ConnectionResetError:
                print("Admin client disconnected unexpectedly.")
                break

    def handle_user(self, conn, username):
        conn.sendall(b'User Menu:\n1. View homework\n2. Add scores\n3. Exit\n')
        while True:
            try:
                choice = conn.recv(1024).decode().strip()
                if choice == '1':
                    with self.hw_lock:
                        if self.homeworks:
                            conn.sendall('\n'.join(self.homeworks).encode() + b'\n')
                        else:
                            conn.sendall(b'No homework assigned!\n')
                elif choice == '2':
                    conn.sendall(b'Enter 5 scores (comma separated): ')
                    try:
                        scores = list(map(int, conn.recv(1024).decode().strip().split(',')))
                        if len(scores) != 5:
                            raise ValueError
                        with self.scores_lock:
                            self.scores[username] = scores
                            self.save_scores()
                        conn.sendall(b'Scores added!\n')
                    except:
                        conn.sendall(b'Invalid input! Please enter 5 numbers separated by commas.\n')
                elif choice == '3':
                    conn.sendall(b'Goodbye!\n')
                    break
                else:
                    conn.sendall(b'Invalid choice!\n')
            except ConnectionResetError:
                print(f"User {username} disconnected unexpectedly.")
                break

    def start(self):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind((HOST, PORT))
            s.listen()
            print(f'Server listening on {HOST}:{PORT}')
            while True:
                conn, addr = s.accept()
                print(f'Connected by {addr}')
                
                conn.sendall(b'Username (1-45): ')
                username = conn.recv(1024).decode().strip()
                
                conn.sendall(b'Password: ')
                password = conn.recv(1024).decode().strip()
                
                if not self.authenticate(username, password):
                    conn.sendall(b'Authentication failed!\n')
                    conn.close()
                    continue
                
                if 1 <= int(username) <= 5:
                    self.handle_admin(conn)
                else:
                    self.handle_user(conn, username)
                
                conn.close()

if __name__ == '__main__':
    server = Server()
    server.start()

auv

import socket
import re

def is_valid_ip(ip):
    pattern = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
    return pattern.match(ip) is not None

while True:
    a = input("请输入IP: ")
    if is_valid_ip(a):
        HOST = a
        break
    else:
        print("无效的IP地址,请重新输入。")

PORT = 65432

def client():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        
        print(s.recv(1024).decode(), end='')
        username = input()
        s.sendall(username.encode() + b'\n')
        
        print(s.recv(1024).decode(), end='')
        password = input()
        s.sendall(password.encode() + b'\n')
        
        response = s.recv(1024).decode()
        print(response)
        
        if 'failed' in response:
            return
        
        if 1 <= int(username) <= 5:
            # Admin menu
            while True:
                data = s.recv(1024).decode()
                print(data)
                if 'Enter choice' in data:
                    choice = input('Enter choice: ')
                    s.sendall(choice.encode() + b'\n')
                    if choice == '1':
                        print(s.recv(1024).decode(), end='')
                        s.sendall(input().encode() + b'\n')
                        print(s.recv(1024).decode())
                    elif choice == '2':
                        data = s.recv(4096).decode()
                        print(data)
                        if 'Current homeworks' in data:
                            s.sendall(input().encode() + b'\n')
                            print(s.recv(1024).decode())
                    elif choice == '3':
                        print(s.recv(4096).decode())
                    elif choice == '4':
                        break
        else:
            # User menu
            while True:
                data = s.recv(1024).decode()
                print(data)
                if 'Enter choice' in data:
                    choice = input('Enter choice: ')
                    s.sendall(choice.encode() + b'\n')
                    if choice == '1':
                        print(s.recv(4096).decode())
                    elif choice == '2':
                        print(s.recv(1024).decode(), end='')
                        s.sendall(input().encode() + b'\n')
                        print(s.recv(1024).decode())
                    elif choice == '3':
                        break

if __name__ == '__main__':
    client()

0 条评论

目前还没有评论...