javascript - 如何使用 Flask 和 Socket.io 加入和离开房间的简明示例?

标签 javascript python jquery flask socket.io

我正在尝试将 socket.io 与连接到 JS 的 Flask 服务器一起使用。基本上我正在努力解决所有问题,但我的第一步是做到这一点,以便用户可以连接到不同的 channel 。我的广播消息功能可以正常工作,但是当我点击不同的 channel 时,消息不会发送到不同的 channel 。我做错了什么?

JS:

document.addEventListener('DOMContentLoaded', ()=>{

  // Send user back to login page if they didn't sign in
  const username = localStorage.getItem('username');
  if (username == null){
    window.location = "/";
  }

  // Switch button active class when clicked
  $('.list-group .list-group-item.list-group-item-action').click(function(e) {
    $('.list-group .list-group-item.list-group-item-action.active').removeClass('active');
    var $this = $(this);
    if (!$this.hasClass('active')) {
        $this.addClass('active');
    }
    e.preventDefault();
  });

  // Connect to socket.io
  var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);

  socket.on('connect', () => {

    // Automatically connect to general channel
    socket.emit('join',{"channel": "general", "username":username});

    // When a channel is clicked, connect to that channel
    document.querySelectorAll('.list-group-item').forEach(function(channel){
      channel.onclick = () =>{
        socket.emit('join',{"channel":channel.innerHTML, "username":username});
        return false;
      }
    });

    // When a message is sent, call 'send message' function from server
    document.querySelector('#send-message').onsubmit = () => {
      const message = document.querySelector('#m').value
      socket.emit('send message', {'message': message});

      // Clear message form
      document.querySelector('#m').value = "";

      return false;
    };
  });



  // Callback from server for sending messages
  socket.on('broadcast message', data =>{
    console.log(data);

    // Append message to list of messages
    const li = document.createElement('li');
    li.innerHTML = `${data.message}`;
    document.querySelector('#messages').append(li);

  });
});

Python flask :

import os

from flask import Flask, render_template, url_for
from flask_socketio import SocketIO, emit, join_room, leave_room
from collections import defaultdict

app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio = SocketIO(app)

messages = defaultdict(list)
channels = ["Programming"]

@app.route("/")
def index():
    return render_template("login.html")

@app.route("/chatroom/")
def chatroom():
    return render_template("chatroom.html", channels=channels, messages=messages)

@socketio.on("send message")
def message(data):
    print(data)
    emit("broadcast message",  {"message": message}, broadcast=True)

@socketio.on('join')
def on_join(data):
    username = data['username']
    channel = data['channel']
    join_room(channel)
    #send(username + ' has entered the room.', channel=channel)

if __name__ == '__main__':
    socketio.run(app)

最佳答案

将一个房间想象成一组留在服务器上的用户。当您在“发送消息”中发送消息时,您设置了 broadcast=True,因此它会将其作为全局消息发送给所有用户,只要他们处于连接状态。如果您只想发送给特定房间的用户,则需要在每次发送消息时从客户端指定要将消息发送到哪个房间,如下所示:

//客户端.js

socket.emit('join', { 'channel': channel, ... });
socket.emit('send message', {'message': message, 'channel': channel});

//服务器.py

@socketio.on("send message")
def message(data):
    room = data['channel']
    emit('broadcast message', data['message'], room=room)

关于javascript - 如何使用 Flask 和 Socket.io 加入和离开房间的简明示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53807546/

相关文章:

javascript - 需要通用和特定的 onclick 事件处理程序

python - 高效地将行添加到 pandas DataFrame

python - Unicode解码错误: 'gbk' codec can't decode bytes

javascript - 获取 li 中每个单词的第一个字母

JQuery 单击事件无法正常工作

javascript - 分配 JSON 数据时,不是 angularjs 中的数组错误

javascript - 403 禁止使用基本身份验证和 ajax 调用 REST API

Javascript:如何显示数组中一定数量的项目并在单击按钮时显示其他项目?

python - SQLAlchemy:joinedload 子条款查询的 order_by(无)?

jquery - 在灯箱弹出窗口中添加内容并设置大小