在onload函数中调用flask_socketio函数

时间:2020-10-28 13:45:38

标签: javascript python flask socket.io

我正在尝试使用flask socket-io从服务器加载/初始化我的白名单文本字段。为此,每当文本字段加载时,我都希望从服务器获取数据。我已编写此javascript代码:

    //Initialisation
    function initWhitelist(){
        socket = io.connect('http://' + document.domain + ':' + location.port);
        socket.on('init_whitelist_received',function(data){
        var text = data['text'];
        alert("hello");
        document.getElementById("whitelist").innerHTML = text;
        })
    };

onload调用有效,并在此处定义:

    <textarea id="whitelist" name="whitelist" onload="initWhitelist()" style="width: 500px; height: 250px; font-size: 18px; font-family: monospace; margin-top: 10px;"> </textarea>

侦听器内没有错误(因为它从未被调用),但是这里是:

#Initially Read Whitelist
@socketio.on('init_whitelist')
def init_whitelist():
    #Receive updated whitelist from the front end HTML
    whitelist = open(r"whitelist.txt","r")
    # Output contents of whitelist
    emit('update_whitelist_received', {'text': whitelist.read()})
    whitelist.close()

我肯定在javascript中犯了一个错误,但是对于我一生来说,我找不到解决方案。任何帮助表示赞赏。

更新 有些人要求提供完整的文件,所以我提供了它们。

索引A

<html>
    <head>
        <!-- Some basic meta info -->
        <title>Dashboard</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-   scale=1">
        <!-- A stylesheet to make things automatically look nice -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.min.css">
    <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
        <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
    <!-- Script to handle socket.io -->
    <script>
        // The http vs. https is important. Use http for localhost!
        socket = io.connect('http://' + document.domain + ':' + location.port);
        //Initialisation
        function initWhitelist(){
            socket = io.connect('http://' + document.domain + ':' + location.port);
            socket.on('init_whitelist_received',function(data){
            var text = data['text'];
            alert("hello");
            document.getElementById("whitelist").innerHTML = text;
            })
        };
        var socket;
        $(document).ready(function() {
            // Button was clicked
            document.getElementById("send_button").onclick = function() {
            // Get the text value
            var text = document.getElementById("textfield_input").value;
            // Update the chat window
            document.getElementById("chat").innerHTML += "You: " + text + "\n\n";

            // Emit a message to the 'send_message' socket
            socket.emit('send_message', {'text':text});
            // Set the textfield input to empty
            document.getElementById("textfield_input").value = "";
            };

            // Message received from server (Goes into LOG textfield)
            socket.on('message_from_server', function(data) {
            var text = data['text'];
            document.getElementById("chat").innerHTML += "Server: " + text +   "\n\n";
            });

            //Update Whitelist Button Clicked
            // Button was clicked
            document.getElementById("update_whitelist_button").onclick = function() {
            // Get the text value
            var upd_white_list = document.getElementById("whitelist").value;
            // Update the chat window
            document.getElementById("chat").innerHTML += "You modified the Whitelist" + "\n";
            //Send updated Whitelist to server
            socket.emit('updated_whitelist',{'text':upd_white_list})
            };


            // Message received from server (Goes into LOG textfield)
            socket.on('update_whitelist_received', function(data) {
            var upd_white_list = data['text'];
            document.getElementById("whitelist").innerHTML = upd_white_list;

            });
             document.getElementById("test_button").onclick = initWhitelist();
        });
    </script>
    </head>
    <body>
    <div style="margin: 25px; display: flex; flex-direction: column;">
        <h1 class="title">Hello {{username}}.</h1>
        <p>Welcome to the dashboard.</p>
        <textarea id="chat" style="width: 500px; height: 250px; font-size: 18px; font-family: monospace; margin-top: 10px;"></textarea>
        <div style="display: flex; flex-direction: row;">
            <input type="text" id="textfield_input" style="height: 30px; width: 400px; margin-top: 5px; margin-right: 10px;" class="textfield">
            <button id="send_button" class="button is-primary" style="margin-top: 5px; width: 90px; height: 30px;">Send</button>
            <button id="test_button" class="button is-primary" style="margin-top: 5px; width: 90px; height: 30px;">Test</button>
        </div>


        <p>Whitelist</p>
        <div>
            <textarea id="whitelist" name="whitelist" onload="initWhitelist()" style="width: 500px; height: 250px; font-size: 18px; font-family: monospace; margin-top: 10px;"> </textarea>
            <button id="update_whitelist_button" class="button is-primary" style="margin-top: 5px; width: 90px; height: 30px;">Update!</button>
        </div>
    </div>
</body>
</html>

Python脚本

from flask import *
from flask_socketio import *

# Init the server
app = Flask(__name__)
app.config['SECRET_KEY'] = 'some super secret key!'
socketio = SocketIO(app, logger=True)


# Send HTML!
@app.route('/')
def root():
    return "Hello World!"


@app.route('/html/<username>')
# Display the HTML Page & pass in a username parameter
@app.route('/html/<username>')
def html(username):
    return render_template('indexA.html', username=username)

# Receive a message from the front end HTML
@socketio.on('send_message')
def message_received(data):
    print(data['text'])
    emit('message_from_server', {'text':'Message recieved!'})

#Initially Read Whitelist
@socketio.on('init_whitelist')
def init_whitelist():
    #Receive updated whitelist from the front end HTML
    emit('init_whitelist_received', {'text': 'debug'})
    whitelist = open(r"whitelist.txt","r")
    # Output contents of whitelist
    emit('init_whitelist_received', {'text': str(whitelist.read())})
    whitelist.close()

@socketio.on('updated_whitelist')
def message_update_whitelist_received(data):
    print(data['text'])
    whitelist = open(r"whitelist.txt","w")
    #Update write list
    whitelist.write(data['text'])
    whitelist.close()
    #Output to Log
    emit('message_from_server', {'text':'Changes to Whitelist Saved!'})
    #Output contents of whitelist
    emit('update_whitelist_received', {'text': data['text']})
    
# Actually Start the App
if __name__ == '__main__':
    """ Run the app. """
    socketio.run(app, port=8000, debug=True)

进行进一步的测试,我确定我不能调用此套接字@ socketio.on('init_whitelist'),但是我不确定如何调用它,因为我没有任何文本要发送到为了触发它。进一步发出请求并没有运行该功能。

1 个答案:

答案 0 :(得分:1)

您正在监听init_whitelist_received事件,但是还需要发出in事件,以便运行侦听器回调。

注册回调后或在init_whitelist事件hadler中发出window.onload事件,它应能按预期工作:

//Initialisation
function initWhitelist(){
  socket = io.connect('http://' + document.domain + ':' + location.port);
  socket.on('init_whitelist_received',function(data){
    var text = data['text'];
    alert("hello");
    document.getElementById("whitelist").innerHTML = text;
  });
  
  // emit init_whitelist
  socket.emit('init_whitelist');
};