|
| 1 | +real-time-chat-app/ |
| 2 | +├── public/ |
| 3 | +│ └── index.html |
| 4 | +├── server.js |
| 5 | +├── package.json |
| 6 | +npm init -y |
| 7 | +npm install express socket.io |
| 8 | +// server.js |
| 9 | +const express = require('express'); |
| 10 | +const http = require('http'); |
| 11 | +const socketIo = require('socket.io'); |
| 12 | + |
| 13 | +const app = express(); |
| 14 | +const server = http.createServer(app); |
| 15 | +const io = socketIo(server); |
| 16 | + |
| 17 | +// Serve the static HTML file |
| 18 | +app.use(express.static(__dirname + '/public')); |
| 19 | + |
| 20 | +io.on('connection', (socket) => { |
| 21 | + console.log('A user connected'); |
| 22 | + |
| 23 | + // Listen for 'join' event |
| 24 | + socket.on('join', (username) => { |
| 25 | + socket.username = username; |
| 26 | + }); |
| 27 | + |
| 28 | + // Listen for 'chat message' event |
| 29 | + socket.on('chat message', (msg) => { |
| 30 | + io.emit('chat message', { username: socket.username, message: msg }); |
| 31 | + }); |
| 32 | + |
| 33 | + // Handle user disconnection |
| 34 | + socket.on('disconnect', () => { |
| 35 | + console.log('A user disconnected'); |
| 36 | + }); |
| 37 | +}); |
| 38 | + |
| 39 | +// Start the server |
| 40 | +server.listen(3000, () => { |
| 41 | + console.log('Server is running on http://localhost:3000'); |
| 42 | +}); |
| 43 | +<!-- public/index.html --> |
| 44 | +<!DOCTYPE html> |
| 45 | +<html> |
| 46 | +<head> |
| 47 | + <title>Real-Time Chat</title> |
| 48 | +</head> |
| 49 | +<body> |
| 50 | + <h1>Real-Time Chat</h1> |
| 51 | + <input id="username" type="text" placeholder="Enter your username"> |
| 52 | + <button id="join">Join Chat</button> |
| 53 | + <ul id="messages"></ul> |
| 54 | + <input id="message" type="text" placeholder="Type your message"> |
| 55 | + <button id="send">Send</button> |
| 56 | + |
| 57 | + <script src="/socket.io/socket.io.js"></script> |
| 58 | + <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> |
| 59 | + <script> |
| 60 | + const socket = io(); |
| 61 | + |
| 62 | + $('#join').click(() => { |
| 63 | + const username = $('#username').val(); |
| 64 | + socket.emit('join', username); |
| 65 | + }); |
| 66 | + |
| 67 | + $('#send').click(() => { |
| 68 | + const message = $('#message').val(); |
| 69 | + socket.emit('chat message', message); |
| 70 | + $('#message').val(''); |
| 71 | + }); |
| 72 | + |
| 73 | + socket.on('chat message', (data) => { |
| 74 | + $('#messages').append($('<li>').text(data.username + ': ' + data.message)); |
| 75 | + }); |
| 76 | + </script> |
| 77 | +</body> |
| 78 | +</html> |
| 79 | +node server.js |
0 commit comments