[英]javascript socket.on(..) is not being called
So I have a simple website that I am working on, for socket communication and chat ability demonstration, where the server is written in python flask app, and the client uses javascript.所以我有一个我正在做的简单网站,用于套接字通信和聊天能力演示,其中服务器使用 python flask 应用程序编写,客户端使用 javascript。 here is a snippet of code from the server:这是来自服务器的一段代码:
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)
as you can see, the server gets a message event and emits a msg_cast event.如您所见,服务器获取消息事件并发出 msg_cast 事件。
where as the client successfully connects:客户端成功连接的位置:
document.addEventListener('DOMContentLoaded', () => {
...
...
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
...
... later on it has: ...后来它有:
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');
});
but then the first alert('message was received ');` is never called, though I know that the server does indeed send the msg_cast message, it never is handled by the client, and I know that if I remove this code form the client everything works fine, except sometimes trouble comes from a different place than expected, and the console shows no issues whatsoever.但随后第一个警报('收到消息');`从未被调用,虽然我知道服务器确实发送了 msg_cast 消息,但它永远不会由客户端处理,我知道如果我从客户端一切正常,除了有时麻烦来自与预期不同的地方,并且控制台没有显示任何问题。
Also, there is a form that should be filled in order for the code to start running, and when I submit the form the page jumps to the start as if it is a sign of some javascript code that is not right.此外,为了让代码开始运行,应该填写一个表单,当我提交表单时,页面会跳转到开头,好像它是一些不正确的 javascript 代码的标志。 can you help?你能帮我吗? see what's wrong and why is the socket.on(msg_cast.. is not called?看看有什么问题,为什么 socket.on(msg_cast.. 没有被调用?
thanks.谢谢。
Found the 3 problems:发现3个问题:
Instead of let id = localStorage('ids_counter');
而不是 let id = localStorage('ids_counter');
I should have let id = localStorage.getItem('ids_counter');
我应该让 id = localStorage.getItem('ids_counter');
This line document.querySelector(id_str).appendChild(cont2);
这一行document.querySelector(id_str).appendChild(cont2);
is failing on 'Uncaught TypeError: Cannot read property 'appendChild' of null'在“未捕获的类型错误:无法读取属性 'appendChild' of null”上失败
It was because of not using getElementById instead when I am using variable id.这是因为当我使用变量 id 时没有使用 getElementById 。
The third and most important is this code:第三个也是最重要的是这段代码:
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 => {
... ...
Because I am inside .onsubmit
handling of an event, I should simply do socket.emit
instead of wrapping around with socket.on ('connect')
.因为我在.onsubmit
处理事件中,所以我应该简单地做socket.emit
而不是用socket.on ('connect')
环绕。 Once I remove this the socket.on
is called.一旦我删除它,就会调用socket.on
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.