Im learning to use socketio with flask(sorry for the horrible code)
and im trying to create a private chat for a social network but when i try to join a room only the first person joins it and the seccond one doesn’t
Server code
from flask import Blueprint, redirect, render_template, request, flash, session, url_for
import sqlite3
from . import socketio
from flask_socketio import join_room, leave_room, emit, send
chat = Blueprint("chat", __name__)
@chat.route("/joinchat", methods=["POST", "GET"])
def joinchat():
if request.method == "POST":
name = request.form.get("name")
con = sqlite3.connect("DB.db")
cur = con.cursor()
cur.execute("SELECT id FROM users WHERE username = ?", (name,))
id = cur.fetchone()
if id:
id = id[0]
con.close()
return redirect("/chat/" + str(id))
else:
con.close()
flash("There is no user with that username", category="error")
return render_template("select_chat.html")
@chat.route("/chat/<int:id>")
def chats(id):
return render_template("chat.html")
@socketio.on("mesage")
def handlemesage(mesage, url):
print(mesage, url)
socketio.emit("postmesage", mesage, to=url)
@socketio.on("connect1")
def connect1(id):
print(id, type(id))
join_room(id)
emit("connectinter", id, broadcast=True)
@socketio.on("connect2")
def connect2(id):
if session["id"] == int(id):
print(id, type(id))
join_room(id)
emit('redirect', "/chat/" + str(id))
Client js
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script>
var socket = io();
$("#send").on("click", function (){
console.log(document.getElementById('inputmesage').value);
socket.emit("mesage", document.getElementById('inputmesage').value, window.location.href.split("/").pop());
});
$("#connect").on("click", function (){
socket.emit("connect1", window.location.href.split("/").pop());
});
socket.on("connectinter", function (id) {
console.log(id);
socket.emit("connect2", id);
});
socket.on('redirect', function (url) {
window.location = url;
});
socket.on("postmesage", function (mesage) {
console.log(mesage)
});
</script>
html
<div class="row">
<div class="col-sm-10">
<input id="inputmesage" class="form-control" type="text">
</div>
<div class="col-sm-2" id="send">
<button type="submit" class="btn btn-outline-warning btn-block align-middle">Send</button>
</div>
</div>
<button id="connect" type="submit" class="btn btn-outline-warning btn-block align-middle">Connect</button>
only the person who clicked the connect button gets joned to the room(connect1)