使用Flask-SocketIO发送私人消息

时间:2020-10-11 13:13:59

标签: python flask socket.io flask-socketio

我正在使用Flask为我的学生制作一个简单的社交媒体网站,现在我创建了实时聊天引擎。我为此任务选择了SocketIO。我正在尝试仅向特定用户发送消息。用户在站点上具有唯一的名称,因此我将这些名称用作其ID,并将房间设置为我们要发送给的所需用户名。但是,当我发送消息时,我会收到我的消息,但是其他用户什么也没收到。我希望接收者实时接收消息。实际上,我不知道这是否是正确的方法,也不知道我对Java语言有一点经验。

app.py

@app.route('/messages')
def messages():
    if 'user_id' in session:
        session['logged_in'] = True
        name = session['name'] //logged-in username
        user_search =request.form.get('user_search') //the desired user who we want to send a message

        room = user_search //now, the room is set to that user
        return render_template('messages.html', name=name, room=room)

    else:
        return redirect('/')


@socketio.on('send_message')
def handle_send_message_event(data):
    app.logger.info("{} has sent message to the room {}: {}".format(data['name'],
                                                                    data['room'],
                                                                    data['message']))
    socketio.emit('receive_message', data, room=data['room'])

app.js

<script>

        const socket = io.connect("http://127.0.0.1:5000");

        socket.on('connect', function () {
        socket.emit('join_room', {
            name: "{{ name }}",
            room: "{{ room }}"
            })

        let message_input = document.getElementById('message_input');

        document.getElementById('message_input_form').onsubmit = function (e) {
            e.preventDefault();
            let message = message_input.value.trim();
            if (message.length) {
                    socket.emit('send_message', {
                    name: "{{ name }}",
                    room: "{{ room }}",
                    message: message
                })
            }
            message_input.value = '';
            message_input.focus();
        }
    });

        socket.on('receive_message', function (data) {
        console.log(data);
        const newNode = document.createElement('div');
        newNode.innerHTML = `<b>${data.name}:&nbsp;</b> ${data.message}`;
        document.getElementById('messages').appendChild(newNode);
    });

    </script>

0 个答案:

没有答案