const WebSocket = require('ws');
const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

const ws = new WebSocket('ws://localhost:8080');

// 定义 currentUser 变量
let currentUser = null;

// 提示用户输入用户名进行注册
function promptForUsername() {
    rl.question('请输入用户名进行注册: ', (username) => {
        if (username.trim() === "") {
            console.log("用户名不能为空，请重新输入。");
            return promptForUsername(); // 重新输入
        }
        ws.send(JSON.stringify({ type: 'register', username }));
    });
}

// 提示用户输入消息
function promptForMessage() {
    rl.question('请输入消息 (或输入 "/exit" 退出): ', (input) => {
        if (input === '/exit') {
            ws.close();  // 关闭连接
            rl.close();  // 关闭命令行
            return;
        }
        
        if (input.startsWith('/private')) {
            const args = input.split(' ');
            if (args.length < 3) {
                console.log("请提供接收者和消息");
                return promptForMessage();
            }
            const recipient = args[1];
            const messageContent = args.slice(2).join(' ');
            ws.send(JSON.stringify({ type: 'private', to: recipient, message: messageContent }));
        } else {
            ws.send(JSON.stringify({ type: 'broadcast', message: `${currentUser}: ${input}` }));
        }

        promptForMessage(); // 继续发送消息
    });
}

ws.on('open', () => {
    console.log('连接到聊天室服务器');
    promptForUsername(); // 直接提示输入用户名
});

ws.on('message', (data) => {
    const message = JSON.parse(data);
    if (message.type === 'register') {
        if (message.success) {
            console.log(message.message);
            currentUser = JSON.parse(data).username; // 将用户名存储在 currentUser
            promptForMessage(); // 注册成功后，提示输入消息
        } else {
            console.log(message.message);
            promptForUsername(); // 注册失败，重新输入用户名
        }
    } else if (message.type === 'broadcast') {
        console.log(`全局消息: ${message.message}`);
    } else if (message.type === 'private') {
        console.log(`[私聊] ${message.from}: ${message.message}`);
    } else if (message.type === 'error') {
        console.log(`错误: ${message.message}`);
    }
});

ws.on('close', () => {
    console.log('与服务器断开连接');
    rl.close();
});const WebSocket = require('ws');

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ port: 8080 });

// 存储客户端信息
const clients = {};
const port = 8080;

// 当有新的连接时
wss.on('connection', (ws) => {
    let currentUser = null;

    ws.on('message', (message) => {
        const parsedMessage = JSON.parse(message);

        // 用户注册处理
        if (parsedMessage.type === 'register') {
            if (clients[parsedMessage.username]) {
                ws.send(JSON.stringify({ type: 'register', success: false, message: '用户名已存在' }));
            } else if (parsedMessage.username.trim() === "") {
                ws.send(JSON.stringify({ type: 'register', success: false, message: '用户名不能为空' }));
            } else {
                // 处理成功注册
                currentUser = parsedMessage.username;
                clients[currentUser] = ws;
                ws.send(JSON.stringify({ type: 'register', success: true, message: '注册成功' }));
                broadcast(`${currentUser} 加入聊天`, currentUser);
            }
        }

        // 检查用户是否注册
        if (!currentUser) {
            ws.send(JSON.stringify({ type: 'error', message: '请先注册您的用户名' }));
            return;
        }

        // 广播消息
        if (parsedMessage.type === 'broadcast') {
            broadcast(parsedMessage.message, currentUser);
        }

        // 点对点私聊
        if (parsedMessage.type === 'private') {
            if (clients[parsedMessage.to]) {
                clients[parsedMessage.to].send(JSON.stringify({ type: 'private', from: currentUser, message: parsedMessage.message }));
            } else {
                ws.send(JSON.stringify({ type: 'private', success: false, message: '用户不在线' }));
            }
        }
    });

    ws.on('close', () => {
        if (currentUser) {
            delete clients[currentUser];
            broadcast(`${currentUser} 离开聊天`, currentUser);
        }
    });
});

// 广播功能
function broadcast(message, sender) {
    for (let username in clients) {
        if (username !== sender) {
            clients[username].send(JSON.stringify({ type: 'broadcast', message }));
        }
    }
}

console.log(`聊天室服务器启动，监听端口 ${port}`);修改代码，当发送信息时没有显示发送信息的用户，