const express = require('express'); const app = express(); const http = require('http').createServer(app); const io = require('socket.io')(http); const path = require('path'); const fs = require('fs'); const messagesFile = path.join(__dirname, 'messages.json'); let chatHistory = []; if (fs.existsSync(messagesFile)) { try { const data = fs.readFileSync(messagesFile); chatHistory = JSON.parse(data); } catch (e) { console.error("Erro ao ler histórico", e); } } app.use(express.static(path.join(__dirname, 'public'))); io.on('connection', (socket) => { socket.emit('chat history', chatHistory); // Gestão do indicador de digitação socket.on('typing', (data) => { socket.broadcast.emit('typing', data); }); socket.on('chat message', (data) => { chatHistory.push(data); if (chatHistory.length > 500) chatHistory.shift(); fs.writeFileSync(messagesFile, JSON.stringify(chatHistory)); io.emit('chat message', data); }); }); const PORT = 3000; http.listen(PORT, () => { console.log(`Servidor de Chat a correr na porta ${PORT}`); });