commit 6cd2ed7249fd01494c994ca0c9b09ee0d0f33c6e Author: sirlilpanda Date: Fri Apr 10 15:29:22 2026 +1200 init diff --git a/README.md b/README.md new file mode 100644 index 0000000..298b289 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +simple chat app \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..17374c2 --- /dev/null +++ b/main.py @@ -0,0 +1,36 @@ +from flask import Flask, render_template, request +from flask_socketio import SocketIO, send, emit, join_room, leave_room + +app = Flask(__name__) +app.config['SECRET_KEY'] = 'your_secret_key' + +socketio = SocketIO(app) + +# Dictionary to store users and their assigned rooms +users = {} + +@app.route('/') +def index(): + return render_template('index.html') + +# Handle new user joining +@socketio.on('join') +def handle_join(username): + users[request.sid] = username # Store username by session ID + join_room(username) # Each user gets their own "room" + emit("message", f"{username} joined the chat", room=username) + +# Handle user messages +@socketio.on('message') +def handle_message(data): + username = users.get(request.sid, "Anonymous") # Get the user's name + emit("message", f"{username}: {data}", broadcast=True) # Send to everyone + +# Handle disconnects +@socketio.on('disconnect') +def handle_disconnect(): + username = users.pop(request.sid, "Anonymous") + emit("message", f"{username} left the chat", broadcast=True) + +if __name__ == '__main__': + socketio.run(app, debug=True) \ No newline at end of file diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..30dec54 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,34 @@ + + + + + Flask WebSocket Chat + + + + +

Flask WebSocket Chat

+ + +
+ + +