簡體   English   中英

javascript socket.on(..) 未被調用

[英]javascript socket.on(..) is not being called

所以我有一個我正在做的簡單網站,用於套接字通信和聊天能力演示,其中服務器使用 python flask 應用程序編寫,客戶端使用 javascript。 這是來自服務器的一段代碼:

import os

from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit

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

@socketio.on("message")
def chat(data):
    mfrom = data["username"]
    channel = data["channel"]
    message = data["message"]
    #print(f"a meesage received from {mfrom}")
    emit("msg_cast", {"username": mfrom, "channel": channel, "message": message}, broadcast=True)

如您所見,服務器獲取消息事件並發出 msg_cast 事件。

客戶端成功連接的位置:

document.addEventListener('DOMContentLoaded', () => {
...
...
  var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
...

...后來它有:

socket.on('msg_cast', data => {

        alert('message was received ');
        let id = localStorage('ids_counter');
        // Create new div content.
        const cont1 = document.createElement('div');
        cont1.className = 'list-group-item list-group-item-action active text-white rounded-0';
        cont1.id = "chat_elem" + id.toString();
        document.querySelector('#list_recent_msgs').appendChild(cont1);
        var id_str = cont1.id;

        id +=1;

        const cont2 = document.createElement('div');
        cont2.className = 'media-body ml-4';
        cont2.id = "chat_elem" + id.toString();
        document.querySelector(id_str).appendChild(cont2);
        var id_str2 = cont2.id;
        id += 1;

        const cont3 = document.createElement('div');
        cont3.className = 'd-flex align-items-center justify-content-between mb-1'
        cont3.id = "chat_elem" + id.toString();
        document.querySelector(id_str2).appendChild(cont3);
        id_str = cont3.id;
        id += 1;

        // added h6 of the sender name
        const cont4 = document.createElement('h6');
        cont4.className = 'mb-0';
        cont4.innerHTML = data.username;
        cont4.id = "chat_elem" + id.toString();
        document.querySelector(id_str).appendChild(cont4);
        id_str = cont3.id;

        // added paragraph of the msg content
        const cont5 = document.createElement('p');
        cont5.className = 'font-italic mb-0 text-small';
        cont5.innerHTML = data.message;
        document.querySelector(id_str2).appendChild(cont5);

        localStorage.setItem('ids_counter', id)
        alert(' done all the job');
       });

但隨后第一個警報('收到消息');`從未被調用,雖然我知道服務器確實發送了 msg_cast 消息,但它永遠不會由客戶端處理,我知道如果我從客戶端一切正常,除了有時麻煩來自與預期不同的地方,並且控制台沒有顯示任何問題。

此外,為了讓代碼開始運行,應該填寫一個表單,當我提交表單時,頁面會跳轉到開頭,好像它是一些不正確的 javascript 代碼的標志。 你能幫我嗎? 看看有什么問題,為什么 socket.on(msg_cast.. 沒有被調用?

謝謝。

發現3個問題:

  1. 而不是 let id = localStorage('ids_counter'); 我應該讓 id = localStorage.getItem('ids_counter');

  2. 這一行document.querySelector(id_str).appendChild(cont2); 在“未捕獲的類型錯誤:無法讀取屬性 'appendChild' of null”上失敗

這是因為當我使用變量 id 時沒有使用 getElementById 。

第三個也是最重要的是這段代碼:

  document.querySelector('#chat_msgs_form').onsubmit = () => {

        var elem = document.getElementById("username_head");
        const username = elem.innerHTML;
        elem = document.getElementById('chat_msg_head');
        const channel = elem.innerHTML;
        elem = document.querySelector('#chat_msg_body');
        const message = elem.value;

        socket.on('connect', () => {
            socket.emit('message', {'username': username, "channel": channel, "message": message});
         });
        //alert(' after connect');
        socket.on('msg_cast', data => {

...

因為我在.onsubmit處理事件中,所以我應該簡單地做socket.emit而不是用socket.on ('connect')環繞。 一旦我刪除它,就會調用socket.on

暫無
暫無

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

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