Frontend Backend Communication Documentation - DSGT-DLP/Deep-Learning-Playground GitHub Wiki

socket.io

socket.io is a module used to establish a WebSocket connection between the Flask Backend and React Frontend for dual communication. It is event-based, so it is completely asynchronous. The information must be sent through one method and must be received someplace else through a different async method. This helps prevent any block in execution in the frontend when passing data to the backend for training or processing and allows for asynchronous communication from the backend to the frontend.

Sending Information from Frontend to Backend:

In any React Component:

import { socket } from '<someRelativePath>/helper_functions/TalkWithBackend'
const MyComponent = () => {
  socket.emit('eventName', data1, data2, ...)
}

In driver.py:

@socket.on('eventName')
def any_name(param1, param2, ...):
    <perform_function>

The eventName needs to be the same, and you do not have to jsonify so you can directly send dictionaries as well.

Sending Information from Backend to Frontend:

You can create a function in driver.py that interacts with socket as shown below, and then pass that function as arguments for use in other backend files

def any_name(param1):
    socket.emit('eventName', f'param1 is {param1}')     # as an example

In a React Component that needs to intercept the data:

import { socket } from '<someRelativePath>/helper_functions/TalkWithBackend'
const MyComponent = () => {
  const [data, setData] = useState(null)
  useEffect(() => {
    socket.on('eventName', (resultData) => {
      setData(resultData)
    })
  }, [socket])
}

Check out driver.py and TrainButton.js for an example of its usage

Resources

Server API: Flask-SocketIO
Client API: socket.io-client

Contact @samarth52 for any socket.io related bugs.