套接字连接似乎没有响应

时间:2019-07-06 14:48:01

标签: javascript flask socket.io

我正在尝试使用Flask和Javascript构建聊天应用程序。我在侧面创建了一个可折叠的导航栏,该导航栏显示了所有可用的房间,一旦网站加载,用户应该在用户单击其他房间的XMLHttpRequest后自动加入一个房间(这里我只是用“ page1”进行测试)被发送以检索该房间中的对话。但是,一旦我有了套接字连接,XMLHttpRequest的问题似乎就没有响应,它发送请求却从不接收?当我删除套接字代码时,一切似乎都可以正常工作。

JavaScript代码:

var username = localStorage.getItem('username');

document.addEventListener("DOMContentLoaded", function() {

  var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
  socket.on('connect', () => {
    socket.emit("join", {"username": username, "room": "page1"});
  });
  // Displays/hides the sidebar
  document.getElementById("toggle").onclick = function() {

    var sidebar = document.getElementById("mySidenav");
    var content = document.getElementById("page-content-wrapper");

    if (sidebar.style.width === "250px") {
      sidebar.style.width = "0";
      content.style.marginLeft = "0";

    } else {
      sidebar.style.width = "250px";
      content.style.marginLeft = "250px"
    }
  };

  // Hides/Displays form for creating a new chatroom
  document.getElementById("create").onclick = function() {
    // Displays a form where a user can create a new chatroom
    document.getElementById("myForm").style.display = "block";
    // Hides the form
    document.getElementById("close").onclick = function() {
      document.getElementById("myForm").style.display = "none";
    };
  };
  // Requests the information in a given room
  // .chat is the class of all the buttons with the room names
  document.querySelectorAll(".chat").forEach(button => {
    button.onclick = () => {
      console.log("Clicked")
      const request = new XMLHttpRequest();
      // requested room
      const room_req = button.innerHTML;
      request.open("GET", `/${room_req}`)
      console.log("Created_Form")
      // Once the request gets the data, update the content to show conversation in the room
      request.onload = () => {
        console.log("Recieved")
        const data = JSON.parse(request.responseText);
        document.getElementById("conv").innerHTML = data.chat
      };
      request.send();
      console.log("Sent form")
      return false;
      };
    });
});

烧瓶代码:

chatrooms = ["page1", "page2"] ## names of chatrooms
users = [ ]
convos = {"page1":"WORKING1", "page2":"WORKING2" } ## dictionary with chatlist_name:conversation
leave_room = { } ## Keeps track of which room a user in currently in

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "GET":
        if "username" in session: # Checks if the current session has a user associated with it
            username = session["username"] # Gets the username associated with the session
            return render_template("index.html", chatrooms=chatrooms, username=username)
        else:
            return render_template("register.html")
    else:
        username = request.form.get("username")
        if username not in users:
            session["username"] = username
        else:
            return render_template("error.html", error="Username already taken")
        return render_template("index.html", chatrooms=chatrooms, username=username)

@app.route("/<room>")
def chatroom(room):
    chat = convos[room]
    return jsonify({"chat":chat})

@app.route("/new_chat", methods=["POST"])
def new_chat():
    ## Make sure the user is logged in
    if "username" not in session:
        return render_template("error.html", error="Please login to create start a new chat")
    else:
        room_name = request.form.get("room_name")
        ## Check if a chatroom with that name already exists
        if room_name in chatrooms:
            return render_template("new_chat.html", name_taken=True)
        else:
            chatrooms.append(room_name)
            return render_template("index.html", chatrooms=chatrooms, username=session["username"])


@app.route("/signout")
def sign_out():
    session.pop("username")
    return redirect(url_for("index"))

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

@socketio.on('join')
def on_join(data):
    username = data['username']
    room = data['room']
    join_room(room)
    leave_room[username] = room
    send(username + ' has entered the room.', room=room)
    return jsonify ({"success": True})

@socketio.on('leave')
def on_leave(data):
    username = data['username']
    room = leave_room[username]
    leave_room(room)
    del leave_room[username]
    send(username + ' has left the room.', room=room)
    return jsonify ({"success": True})

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

0 个答案:

没有答案