If the the other user submit the other users key that will send the message. its like sending message to unique username
Generate Unique Key for every user
import string
import random
def generate_key():
key_length = 4
characters = string.digits
return ''.join(random.choice(characters) for _ in range(key_length))
generated_key=generate_key()
print(generated_key)
Its a 4 digit key for testing purpose. In real application must use long key with other randomness to make sure two key will not be same. Instead of key we can use unique user name. Thas another topic . For simplicity we will use this 4 digit key. Uptate it later on your necessary.
Our application structure….
stept by step Explanation
when the user load the page on borwer they will go to this page
If the user diconnected we will remove the user from the python dictionary.( its like active user management)
@socketio.on('disconnect')
def on_disconnect():
print('User disconnected')
for key, sid in active_connections.items():
if sid == request.sid:
del active_connections[key]
break
When the user will send menssage to specific user.( the logic handles on serverside socketio)
@socketio.on('send_message')
def send_message(data):
key = data['key']
message = data['message']
if key in active_connections:
recipient_sid = active_connections[key]
emit('receive_message', {'message': message}, to=recipient_sid)
else:
emit('receive_message', {'message': 'Does not Match'}, to=request.sid)
The Complete Server Side code
from flask import Flask, render_template,request
from flask_socketio import SocketIO, emit
import random
import string
app = Flask(__name__)
socketio = SocketIO(app)
active_connections = {}
def generate_key():
key_length = 4
characters = string.digits
return ''.join(random.choice(characters) for _ in range(key_length))
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect')
def on_connect():
print('User connected')
key = generate_key()
active_connections[key] = request.sid
emit('key_assigned', {'key': key})
@socketio.on('disconnect')
def on_disconnect():
print('User disconnected')
for key, sid in active_connections.items():
if sid == request.sid:
del active_connections[key]
break
@socketio.on('send_message')
def send_message(data):
key = data['key']
message = data['message']
if key in active_connections:
recipient_sid = active_connections[key]
emit('receive_message', {'message': message}, to=recipient_sid)
else:
emit('receive_message', {'message': 'Does not Match'}, to=request.sid)
if __name__ == '__main__':
socketio.run(app, debug=True)
the client side code( the code we will send to browser when load the landing page index.html)
Step by step guide First add the scoketuio client side library
Add html content to show the message and users key
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Python Scoketio Chat Prototype</h1>
<!--User unique key will be shows here -->
<p>Your Unique Key: <span id="uniqueKey"></span></p>
<!--This is where user will enter the friends key to send message to friend -->
<input type="text" id="friendKey" placeholder="Enter Friend's Key"><br>
<button onclick="startChat()">Start Chat</button><br>
<!-- This is where the send and received message will shown
<div id="chat"></div>
<!-- This is where user will write the message
<div>
<input type="text" id="messageInput" placeholder="Enter your message">
<button onclick="sendMessage()">Send</button>
</div>
<script>
</script>
</body>
</html>
First run the code. and open the localhost link http://127.0.0.1:5000/ in the browser. Another one in in new incognito mode
So it will act like two unique user for your testing. Then Enter the other users unique key ( which works like unique username here) Then send message . Thats all. customize the code your necessary. Happy coding!
One of the best ajax applied in real world is username checker. In this example we will check if there is existing username
This is code /project we will
use ajax to search username
if username exist or does not exist send to message to the user
Also create new user with html form and flask if username exists
Our first step: Check if username exists or not
Imagine we have this existing username
# Sample list of existing usernames
existing_usernames = ["user1", "user2", "user3"]
when the user enter a username we will check it from server(Check username)
@app.route('/check_username', methods=['POST'])
def check_username():
username = request.form['username']
print(username)
if username in existing_usernames:
return jsonify({'message': 'Username already exists! Please choose a different username.'})
elif not is_valid_username(username):
return jsonify({'message': 'Username contains special characters. Only letters, numbers, and underscores are allowed.'})
else:
return jsonify({'message': 'Username is available!'})
When new account is created username will be added to the username list (Create New User)
@app.route('/create_profile', methods=['POST'])
def create_profile():
username = request.form['username']
if username not in existing_usernames:
existing_usernames.append(username)
return jsonify({'message': f"Welcome, {username}! Your profile has been created successfully."})
else:
return jsonify({'message': 'Username already exists! Please choose a different username.'})
In the client side we are using jquery to make everything simpler.
When the user will type it will automatically send to server with ajax and return the response
We will also make sure if the username exists the response text will show in green color if not it will show in red color.
$(document).ready(function () {
$('#username').keyup(function () {
var username = $(this).val();
if (username.length === 0) {
$('#usernameMessage').text("");
return;
}
if (/\s/.test(username)) {
$('#usernameMessage').text("Username cannot contain spaces.");
return;
}
if (!/^[a-zA-Z0-9]+$/.test(username)) {
$('#usernameMessage').text("Username cannot contain special characters.");
return;
}
$.ajax({
type: 'POST',
url: '/check_username',
data: { 'username': username },
success: function (response) {
$('#usernameMessage').text(response.message);
if (response.message === 'Username is available!') {
$('#usernameMessage').css('color', 'green');
} else {
$('#usernameMessage').css('color', 'red');
}
}
});
});
$('#createProfileForm').submit(function (e) {
e.preventDefault();
var username = $('#username').val();
if (username.length === 0) {
$('#usernameMessage').text("Username cannot be empty.");
return;
}
if (/\s/.test(username)) {
$('#usernameMessage').text("Username cannot contain spaces.");
return;
}
if (!/^[a-zA-Z0-9]+$/.test(username)) {
$('#usernameMessage').text("Username cannot contain special characters.");
return;
}
$.ajax({
type: 'POST',
url: '/create_profile',
data: { 'username': username },
success: function (response) {
$('#usernameMessage').text(response.message);
}
});
});
});
import re
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
# Sample list of existing usernames
existing_usernames = ["user1", "user2", "user3"]
def is_valid_username(username):
# Double check
return re.match("^[a-zA-Z0-9_]*$", username) is not None
@app.route('/')
def index():
return render_template('username-id-generate.html')
@app.route('/check_username', methods=['POST'])
def check_username():
username = request.form['username']
print(username)
if username in existing_usernames:
return jsonify({'message': 'Username already exists! Please choose a different username.'})
elif not is_valid_username(username):
return jsonify({'message': 'Username contains special characters. Only letters, numbers, and underscores are allowed.'})
else:
return jsonify({'message': 'Username is available!'})
@app.route('/create_profile', methods=['POST'])
def create_profile():
username = request.form['username']
if username not in existing_usernames:
existing_usernames.append(username)
return jsonify({'message': f"Welcome, {username}! Your profile has been created successfully."})
else:
return jsonify({'message': 'Username already exists! Please choose a different username.'})
if __name__ == '__main__':
app.run(debug=True)