Flask socket io not emitting any data to React frontend

Viewed 60

I am trying to emulate realtime terminal logs that comes from backend using Flask Socket IO and ReactJS.

It shows socket id and the connected status but no data from "output" not showing in the console. Is there anyway to solve this issue?

Thanks in advance!

Here's my Flask implementation

from flask import Flask, request, Response, jsonify
from flask_socketio import SocketIO, emit
import subprocess


app = Flask(__name__)
app.config["SECRET KEY"] = "mykey"

socketio = SocketIO(app, cors_allowed_origins="*")

def shell_run():
    try:
        # cmd = "seq 1 20"
        cmd = "ping www.google.lk"

        process = subprocess.Popen(
            cmd,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
        )

        while True:
            next_line = process.stdout.readline()
            if next_line:
                print(next_line)
                indices = [49, 63]
                parts = [next_line[i:j] for i, j in zip(indices, indices[1:] + [None])]
                # print(parts[0])
                # socketio.emit("output", "parts[0])")
                socketio.emit("output", next_line)
                socketio.sleep(2)
            elif not process.poll():
                break

    except Exception as e:
        print(e)


@socketio.on("connect")
def frontend_connection():
    print("Client is Connected")
    emit("status", "Connection Established")
    shell_run()


if __name__ == "__main__":
    socketio.run(app, host='0.0.0.0', debug = True)

Here's my ReactJS implementation

import React, { Component } from "react";
import Terminal from "react-terminal-view";
import { io } from "socket.io-client";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      lines: ["Terminal Logs"],
    };
  }

  componentDidMount() {
    console.log("componentDidMount");

    const socket = io.connect('http://127.0.0.1:5000/cmd/');

    socket.on("status", (data) => {
      console.log("socket connected - " + socket.connected);
      console.log("socket id - " + socket.id);
      console.log(data);
    });

    socket.on("output", (data) => {
      console.log(data);
    });
  }

  render() {
    return (
      <div>
        <Terminal lines={this.state.lines} />
      </div>
    );
  }
}

0 Answers
Related