Node.js with Kafka example for chat application, make more simple and easy.
To create a Kafka-based chat application using JavaScript that runs in a web browser, you can use the KafkaJS library for interacting with Apache Kafka. You will also need a WebSocket server to enable communication between the browser and the Kafka broker. Here's how you can set it up:
### Prerequisites:
1. **Kafka Broker**: Ensure you have a Kafka broker running and accessible from your WebSocket server.
2. **WebSocket Server**: Set up a WebSocket server (e.g., using Node.js with the `ws` library) to handle WebSocket connections from the browser and communicate with the Kafka broker.
### WebSocket Server (Node.js with `ws` library):
```javascript
const WebSocket = require('ws');
const { Kafka } = require('kafkajs');
const wss = new WebSocket.Server({ port: 8080 });
const kafka = new Kafka({
clientId: 'chat-app',
brokers: ['localhost:9092'], // Kafka broker address
});
const producer = kafka.producer();
wss.on('connection', (ws) => {
ws.on('message', async (message) => {
try {
// Send the message to Kafka
await producer.send({
topic: 'chat',
messages: [{ value: message }],
});
} catch (error) {
console.error(`Error sending message to Kafka: ${error.message}`);
}
});
});
async function run() {
await producer.connect();
}
run().catch(console.error);
```
HTML and JavaScript (Client-Side):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kafka Chat</title>
</head>
<body>
<input type="text" id="messageInput" placeholder="Type your message...">
<button onclick="sendMessage()">Send</button>
<ul id="chatMessages"></ul>
<script>
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('message', (event) => {
const chatMessages = document.getElementById('chatMessages');
const li = document.createElement('li');
li.textContent = event.data;
chatMessages.appendChild(li);
});
function sendMessage() {
const messageInput = document.getElementById('messageInput');
const message = messageInput.value;
if (message.trim() !== '') {
socket.send(message);
messageInput.value = '';
}
}
</script>
</body>
</html>
```
In this setup, the WebSocket server listens for incoming WebSocket connections on port 8080. When a message is received from the browser, it is sent to the 'chat' Kafka topic using the Kafka producer.
On the client-side, a simple HTML form allows users to type and send messages. Messages received from Kafka are displayed in a list. Remember to adjust the Kafka broker address in the WebSocket server code according to your setup.