简体   繁体   中英

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. 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.

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.

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. can you help? see what's wrong and why is the socket.on(msg_cast.. is not called?

thanks.

Found the 3 problems:

  1. Instead of let id = localStorage('ids_counter'); I should have let id = localStorage.getItem('ids_counter');

  2. This line document.querySelector(id_str).appendChild(cont2); is failing on 'Uncaught TypeError: Cannot read property 'appendChild' of null'

It was because of not using getElementById instead when I am using variable id.

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') . Once I remove this the socket.on is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM