To build a chat application with Node.js and WebSockets, you can follow these steps:
1. Set up a new Node.js project by creating a new directory and running `npm init` to generate a `package.json` file.
2. Install the necessary dependencies by running the following command:
“`
npm install express socket.io
“`
3. Create a new file called `server.js` and require the necessary modules:
“`javascript
const express = require(‘express’);
const app = express();
const http = require(‘http’).createServer(app);
const io = require(‘socket.io’)(http);
“`
4. Set up the basic Express server by defining a route to serve the HTML file:
“`javascript
app.get(‘/’, (req, res) => {
res.sendFile(__dirname + ‘/index.html’);
});
“`
5. Set up the WebSocket connection by listening for incoming connections and handling events:
“`javascript
io.on(‘connection’, (socket) => {
console.log(‘A user connected’);
socket.on(‘disconnect’, () => {
console.log(‘A user disconnected’);
});
socket.on(‘chat message’, (msg) => {
console.log(‘message: ‘ + msg);
io.emit(‘chat message’, msg);
});
});
“`
6. Create the HTML file (`index.html`) that will be served by the Express server:
“`html
<!DOCTYPE html>
<html>
<head>
<title>Chat Application</title>
</head>
<body>
<ul id="messages"></ul>
<form id="chat-form">
<input id="message-input" autocomplete="off" />
<button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const form = document.getElementById(‘chat-form’);
const input = document.getElementById(‘message-input’);
const messages = document.getElementById(‘messages’);
form.addEventListener(‘submit’, (e) => {
e.preventDefault();
if (input.value) {
socket.emit(‘chat message’, input.value);
input.value = ”;
}
});
socket.on(‘chat message’, (msg) => {
const li = document.createElement(‘li’);
li.textContent = msg;
messages.appendChild(li);
});
</script>
</body>
</html>
“`
7. Start the server by adding the following code at the end of `server.js`:
“`javascript
const PORT = process.env.PORT || 3000;
http.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
“`
8. Run the server by executing `node server.js` in the terminal.
Now, you should have a chat application running on `http://localhost:3000`. Multiple users can connect to the application and send messages to each other in real-time.