Python Kafka Server Code and Client on Javascript with Browser

Python at server side and Javascript at client side

Certainly! Here's an example of a Kafka-based chat application with the WebSocket server implemented in Python using the `websockets` library, and the client-side code in JavaScript:


### WebSocket Server (Python with `websockets` library):

```python

import asyncio

import websockets

from kafka import KafkaProducer


async def chat_server(websocket, path):

producer = KafkaProducer(bootstrap_servers='localhost:9092') # Kafka broker address


async for message in websocket:

# Send the message to Kafka

producer.send('chat', value=message.encode('utf-8'))


start_server = websockets.serve(chat_server, 'localhost', 8765) # WebSocket server address


asyncio.get_event_loop().run_until_complete(start_server)

asyncio.get_event_loop().run_forever()

```


### 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:8765');


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 example, the Python WebSocket server listens for incoming WebSocket connections on `localhost:8765`. Messages received from the browser are sent to the 'chat' Kafka topic using the Kafka producer. Messages received from Kafka are displayed in a list in the browser. Make sure to adjust the Kafka broker address in the Python server code according to your setup.


Using KAFKA AND Node.js - Javascript code for chat application run in browser
Broker is always key important.