const http = require('http');
const server = http.createServer();
const { Server } = require('socket.io');
const io = new Server(server);
const port = 8080;
io.on('connection', (socket) => {
console.log('a user connected');
// Send a welcome message to the connected client
socket.emit('welcome', 'Welcome to Socket.io!');
// Broadcast to all clients when a new user connects
socket.broadcast.emit('userJoined', 'A new user has joined the chat');
// Handle chat messages
socket.on('chatMessage', (message) => {
console.log('message received: ' + message);
// Broadcast the message to all clients
io.emit('chatMessage', message);
});
// Handle disconnect
socket.on('disconnect', () => {
console.log('user disconnected');
io.emit('userLeft', 'A user has left the chat');
});
});
server.listen(port, () => {
console.log(`Socket.io server running at http://localhost:${port}`);
});