簡體   English   中英

SocketIO 和 Flask 不顯示消息

[英]SocketIO and Flask not displaying messages

我在使用帶有 socketio 的 JQquery 時遇到了一些麻煩。 我希望用戶在文本框中鍵入的消息在聊天頁面的開頭顯示為列表,但不知何故未能做到這一點。 有人知道我的錯誤在哪里嗎?

相關flask代碼:


    from flask import Flask, render_template, request, flash, session, redirect
from flask_session import Session
from flask_socketio import SocketIO, send, emit

app = Flask(__name__)
app.static_folder = "static"
app.secret_key = "My_secret_key"
app.config["SECRET KEY"] = "another_secret!"
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
socketio = SocketIO(app)


@app.route('/')
def login_form():
    return render_template('index.html')


@app.route('/chat-page', methods=["POST"])
def chat_page():
    username = request.form.get("user_name")
    session["user"] = username
    return render_template('chat-page.html', Uname=username)


@app.route("/logout")
def logout():
    session.pop("user", None)
    flash("You have been logged out!")
    return redirect("/")


# function to send messages to the entire group
@socketio.on("message")
def handle_message(msg):
    print("message: " + msg)
    send(msg, broadcast=True)


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

以及相關的 html 頁面與 jquery:


html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> Flask Lan Chat App</title>
    <link rel="stylesheet" type="text/css" href="{{url_for('static', filename='styles.css')}}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

</head>

<body style="background-image: radial-gradient(circle, #4EFECD, #000000);">


    <section class="hero">
        <div class="hero-container">
        <div class="hero-area">
            <div class="hero-text">
                <h1> Hello {{Uname}}! </h1>
            </div>
        </div>
        </div>
    </section>




    <div class="message_container">
            <div class="d-inline-flex p-2">
                <div class="card" style="width: 30rem;">
                    <div class="card-body">
                        <ul id="messages">
                            <li>Hello World!</li>
                            <li>Hello World!</li>
                            <li>Hello World!</li>
                            <li>Hello World!</li>
                            <li>Hello World!</li>
                        </ul>
                    </div>
                </div>
            </div>
    </div>




    <!-- styling the form and buttons -->
   <div class="chat_page_container">
        <div class="d-inline-flex p-2">
                <div class="input-group">
                    <span class="input-group-text">What say you?</span>
                        <textarea id="MyMessage" class="form-control" aria-label="With textarea"></textarea>
                </div>
               <div class="chat_page_container">
                    <div class="d-inline-flex p-2">
                    <button type="button" id="SendButton"class="btn btn-primary">Say it!</button>
                </div>
                </div>
                 <div class="chat_page_container">
                      <a href="/logout">
                        <button type="button" class="btn btn-warning">Logout!</button>
                      </a>
                </div>
        </div>
    </div>
        <!-- end of styling the form and buttons -->



</body>
   <footer class="bg-dark text-center text-lg-start" style="position: absolute; bottom: 0; width: 100%;">
  <!-- Copyright -->
  <div class="text-center p-3" style="background-color: #1c1d25; color: white;">
    © 2022 Copyright:
    <a class="text-light" href="https://beatrix-droid.github.io/">Beatrice Federici</a>
  </div>
<!-- Copyright -->
    </footer>



<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
    <script type=text/javascript">
       socket.on("connect", function(){
        socket.send("User has connected");
        });

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

       //sending a message and clearing the input box once the message has been sent
       $("#SendButton").on("click", function() {
          socket.send($("#MyMessage").val());
          $("#MyMessage").val("");
       });
     });


    </script>
</html>

任何有關此事的幫助將不勝感激!

我可以告訴你,你的代碼確實有效。
您應該注意拼寫錯誤並完全采用代碼示例。 我對您的代碼進行了一些整理並添加了缺失的部分。
玩得開心。

<html>
  <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Flask Lan Chat App</title>
      <link rel="stylesheet" type="text/css" href="{{url_for('static', filename='styles.css')}}">
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  </head>
  <body style="background-image: radial-gradient(circle, #4EFECD, #000000);">
    <section class="hero">
      <div class="hero-container">
        <div class="hero-area">
          <div class="hero-text">
            <h1>Hello {{Uname}}!</h1>
          </div>
        </div>
      </div>
    </section>

    <div class="message_container">
      <div class="d-inline-flex p-2">
        <div class="card" style="width: 30rem;">
          <div class="card-body">
            <ul id="messages">
            </ul>
          </div>
        </div>
      </div>
    </div>

     <div class="chat_page_container">
      <div class="d-inline-flex p-2">
        <div class="input-group">
          <span class="input-group-text">What say you?</span>
          <textarea id="MyMessage" class="form-control" aria-label="With textarea"></textarea>
        </div>
        <div class="chat_page_container">
          <div class="d-inline-flex p-2">
            <button type="button" id="SendButton"class="btn btn-primary">Say it!</button>
          </div>
        </div>
        <div class="chat_page_container">
          <a href="/logout">
            <button type="button" class="btn btn-warning">Logout!</button>
          </a>
        </div>
      </div>
    </div>

    <footer class="bg-dark text-center text-lg-start" style="position: absolute; bottom: 0; width: 100%;">
      <div class="text-center p-3" style="background-color: #1c1d25; color: white;">
        © 2022 Copyright:
        <a class="text-light" href="https://beatrix-droid.github.io/">Beatrice Federici</a>
      </div>
    </footer>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
    <script type="text/javascript">
      var socket = io();
      socket.on("connect", function(){
        socket.send("User has connected");
      });

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

      $("#SendButton").on("click", function() {
        socket.send($("#MyMessage").val());
        $("#MyMessage").val("");
      });
    </script>

  </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM