const WebSocket = require('ws');

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: '注册成功', username: currentUser }));
                broadcast(`${currentUser} 加入聊天`, currentUser);
            }
            return; 
        }

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

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

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

    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}`);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');

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(' ', (input) => {
        if (input === '/exit') {
            ws.close();  
            rl.close();  
            return;
        }

        if (input.startsWith('@')) {
            const index = input.indexOf(' '); 
            if (index === -1) {
                console.log("私聊格式为 '@ 用户名 消息'");
                return promptForMessage();
            }
            const recipient = input.substring(1, index).trim();
            const messageContent = input.substring(index + 1).trim(); 

            if (!messageContent) {
                console.log("请提供消息内容");
                return promptForMessage();
            }

            ws.send(JSON.stringify({ type: 'private', to: recipient, message: messageContent }));
        } else {
            // 普通消息
            ws.send(JSON.stringify({ type: 'broadcast', message: 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 = message.username; 
            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();
});写一个实验心得