gpt4 book ai didi

javascript socket.on(..) 没有被调用

转载 作者:行者123 更新时间:2023-12-02 21:10:53 24 4
gpt4 key购买 nike

所以我正在开发一个简单的网站,用于套接字通信和聊天能力演示,其中服务器是用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); 因“Uncaught TypeError: Cannot read property '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 就会被调用。

关于javascript socket.on(..) 没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61101526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com