Advertisement
sourav8256

socket.io

Jul 26th, 2023
647
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. npm install express socket.io
  2.  
  3.  
  4.  
  5. const express = require('express');
  6. const app = express();
  7. const http = require('http').Server(app);
  8. const io = require('socket.io')(http);
  9.  
  10. const port = 3000;
  11.  
  12. // Serve the client-side files
  13. app.use(express.static('public'));
  14.  
  15. // Store connected clients
  16. const clients = new Set();
  17.  
  18. // Broadcast messages to all connected clients
  19. function broadcast(message) {
  20.   io.emit('message', message);
  21. }
  22.  
  23. // Handle new connections
  24. io.on('connection', (socket) => {
  25.   clients.add(socket);
  26.  
  27.   // Handle incoming messages from clients
  28.   socket.on('message', (message) => {
  29.     broadcast(message);
  30.   });
  31.  
  32.   // Handle client disconnections
  33.   socket.on('disconnect', () => {
  34.     clients.delete(socket);
  35.   });
  36. });
  37.  
  38. // Start the server
  39. http.listen(port, () => {
  40.   console.log(`Server listening on http://localhost:${port}`);
  41. });
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49. <!DOCTYPE html>
  50. <html>
  51.  
  52. <head>
  53.   <title>Chat App</title>
  54. </head>
  55.  
  56. <body>
  57.   <h1>Chat App</h1>
  58.   <div>
  59.     <textarea id="chatLog" rows="10" cols="40" readonly></textarea>
  60.   </div>
  61.   <div>
  62.     <input type="text" id="message" placeholder="Type your message here">
  63.     <button onclick="sendMessage()">Send</button>
  64.   </div>
  65.  
  66.   <script src="/socket.io/socket.io.js"></script>
  67.   <script>
  68.     const chatLog = document.getElementById('chatLog');
  69.     const messageInput = document.getElementById('message');
  70.     const socket = io();
  71.  
  72.     // Update the chat log when a new message is received
  73.     socket.on('message', function (message) {
  74.       chatLog.value += message + '\n';
  75.     });
  76.  
  77.     // Send the message to the server
  78.     function sendMessage() {
  79.       const message = messageInput.value;
  80.       if (message.trim() !== '') {
  81.         socket.emit('message', message);
  82.         messageInput.value = '';
  83.       }
  84.     }
  85.   </script>
  86. </body>
  87.  
  88. </html>
  89.  
  90.  
  91.  
  92.  
  93.  
  94.  
  95.  
  96.  
  97.  
  98.  
  99.  
  100.  
  101.  
  102.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement