Skip to content

Instantly share code, notes, and snippets.

@bhaireshm
Created July 6, 2024 16:24
Show Gist options
  • Save bhaireshm/ca7112c8a5e3e2aad07d3bfb39b1fe06 to your computer and use it in GitHub Desktop.
Save bhaireshm/ca7112c8a5e3e2aad07d3bfb39b1fe06 to your computer and use it in GitHub Desktop.
// app.js
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const mongoose = require('mongoose');
const messageSchema = new mongoose.Schema({
user: String,
text: String,
timestamp: { type: Date, default: Date.now },
});
const Message = mongoose.model('Message', messageSchema);
module.exports = Message;
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/real-time-logging-app');
// Create an Express app
const app = express();
// Create an HTTP server
const server = http.createServer(app);
// Create a Socket.io server
const io = socketIO(server);
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
// Listen for incoming chat messages
socket.on('chat message', (data) => {
console.log('Received message:', data);
// Save the message to MongoDB
const message = new Message({ user: data.user, text: data.message });
message.save().then(err => {
if (!err) {
console.error('Error saving message to database:', err);
} else {
console.log('Message saved to the database');
}
});
// Broadcast the message to all connected clients
io.emit('chat message', data);
});
// Listen for user disconnection
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
app.use(express.static('public'));
// Start the server
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment