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):


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




### HTML and JavaScript (Client-Side):


<!DOCTYPE html>

<html lang="en">


<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Kafka Chat</title>



<input type="text" id="messageInput" placeholder="Type your message...">

<button onclick="sendMessage()">Send</button>

<ul id="chatMessages"></ul>


const socket = new WebSocket('ws://localhost:8765');

socket.addEventListener('message', (event) => {

const chatMessages = document.getElementById('chatMessages');

const li = document.createElement('li');

li.textContent =;



function sendMessage() {

const messageInput = document.getElementById('messageInput');

const message = messageInput.value;

if (message.trim() !== '') {


messageInput.value = '';







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.