0

I have a basic chat that works fine, however when a user opens another page (/chat and /profile at same time) I get another connection, and same user will have duplicated sessions in the chat page.

What I am looking for a way to avoid this behavior. Maybe allow sockets only in /chat page?

main.py

....

@socketio.on('message')
def handleMessage(msg):
    print ('Message: ' , msg)
    send(msg, broadcast=True)

chart.html

var socket = io.connect('http://192.168.56.10/');

socket.on('connect', function() {
    socket.send('User has connected!');
});

socket.on('message', function(msg) {
    $("#messages_chat").append('<li>' + msg + '</li>');
    console.log("receive messages");
});

$("#sendbutton").on('click', function() {
    socket.send($('#myMessage').val());
    $('#myMessage').val('');
});

views.py

....
@mod.route('/chat',  methods=['GET'])
@login_required
def chat():
    return render_template("users/chat.html")
user455318
  • 3,280
  • 12
  • 41
  • 66
  • I don't follow. If the user navigates from /chat to /profile, then the connection from /chat will end, the browser will do that for you. If the /chat and /profile pages are opened in two separate tabs, or two separate browsers, then it is expected that they each will have its own connection to the server. So what's the problem? – Miguel Grinberg Nov 15 '16 at 03:32
  • @Miguel if /chat and /profile pages are opened at same time, they have two connections, but in terms of functionality a chat should only allow an unique "persona" if the connections are from the same user (e.g. same login). Otherwise I will have two messages saying "Miguel has entered in the room". Should I use a list to check if the user is already in the room and avoid the second hello message? – user455318 Nov 15 '16 at 09:20
  • 1
    Yes. Users and connections are not the same thing. A user can have more than one connection, if these need to be consolidated for certain actions, it is up to the application to implement that. – Miguel Grinberg Nov 15 '16 at 16:56

0 Answers0