Skip to content

Instantly share code, notes, and snippets.

@navaneeth-dev
Created February 22, 2024 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navaneeth-dev/45f68f0bec2653160ae3db538e2dd550 to your computer and use it in GitHub Desktop.
Save navaneeth-dev/45f68f0bec2653160ae3db538e2dd550 to your computer and use it in GitHub Desktop.
LAN group chat
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Group Chat</title>
<script>
// Function to initialize WebSocket connection
function initWebSocket() {
// WebSocket connection URL
var wsUri = "ws://localhost:8765";
// Create WebSocket instance
var websocket = new WebSocket(wsUri);
// Function to handle incoming messages
websocket.onmessage = function(evt) {
// Append the received message to the chat area
var chatArea = document.getElementById("chat-area");
chatArea.innerHTML += evt.data + "<br>";
};
// Function to handle sending messages
function sendMessage() {
var messageInput = document.getElementById("message-input");
var message = messageInput.value;
// Send the message to the server
websocket.send(message);
// Clear the input field
messageInput.value = "";
}
// Set up event listener for the send button
var sendButton = document.getElementById("send-button");
sendButton.addEventListener("click", sendMessage);
}
</script>
</head>
<body onload="initWebSocket()">
<div id="chat-area" style="height: 300px; overflow-y: scroll;"></div>
<input type="text" id="message-input" placeholder="Type your message...">
<button id="send-button">Send</button>
</body>
</html>
import asyncio
import websockets
import http.server
import socketserver
import threading
# Store connected clients
connected = set()
async def chat_server(websocket, path):
# Add new client to connected clients
connected.add(websocket)
try:
async for message in websocket:
# Broadcast received message to all connected clients
for client in connected:
await client.send(message)
finally:
# Remove client when they disconnect
connected.remove(websocket)
async def main():
# Start the WebSocket server
async with websockets.serve(chat_server, "localhost", 8765):
await asyncio.Future() # Wait forever
# Serve the HTML file
def serve_html():
PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
if __name__ == "__main__":
# Start the WebSocket server
websocket_thread = threading.Thread(target=asyncio.run, args=(main(),))
websocket_thread.start()
# Start serving HTML file
serve_html()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment