Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- npm install express socket.io
- const express = require('express');
- const app = express();
- const http = require('http').Server(app);
- const io = require('socket.io')(http);
- const port = 3000;
- // Serve the client-side files
- app.use(express.static('public'));
- // Store connected clients
- const clients = new Set();
- // Broadcast messages to all connected clients
- function broadcast(message) {
- io.emit('message', message);
- }
- // Handle new connections
- io.on('connection', (socket) => {
- clients.add(socket);
- // Handle incoming messages from clients
- socket.on('message', (message) => {
- broadcast(message);
- });
- // Handle client disconnections
- socket.on('disconnect', () => {
- clients.delete(socket);
- });
- });
- // Start the server
- http.listen(port, () => {
- console.log(`Server listening on http://localhost:${port}`);
- });
- <!DOCTYPE html>
- <html>
- <head>
- <title>Chat App</title>
- </head>
- <body>
- <h1>Chat App</h1>
- <div>
- <textarea id="chatLog" rows="10" cols="40" readonly></textarea>
- </div>
- <div>
- <input type="text" id="message" placeholder="Type your message here">
- <button onclick="sendMessage()">Send</button>
- </div>
- <script src="/socket.io/socket.io.js"></script>
- <script>
- const chatLog = document.getElementById('chatLog');
- const messageInput = document.getElementById('message');
- const socket = io();
- // Update the chat log when a new message is received
- socket.on('message', function (message) {
- chatLog.value += message + '\n';
- });
- // Send the message to the server
- function sendMessage() {
- const message = messageInput.value;
- if (message.trim() !== '') {
- socket.emit('message', message);
- messageInput.value = '';
- }
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement