simple-chat/server/server1.js
2024-09-27 11:41:21 +08:00

38 lines
967 B
JavaScript

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
const app = express();
const server1 = http.createServer(app);
const io = socketIo(server1);
// Serve static files from the public directory
app.use(express.static(path.join(__dirname, 'public')));
// Socket.IO connection
io.on('connection', (socket) => {
console.log('A user connected');
// Listen for chat message
socket.on('chat message', (msg) => {
io.emit('chat message', msg); // Broadcast the message to all clients
});
// Listen for image
socket.on('image', (img) => {
io.emit('image', img); // Broadcast the image to all clients
});
// Handle disconnection
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
// Start the server
const PORT = process.env.PORT || 3000;
server1.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});