socket.io client from electron app doesn't connect to flask server unless the server is started first

Viewed 12

I have a socket.io client that I'm running inside an electron app. The app is connecting to a flask server running flask_socketio. This all works great, unless the client is started before the server, in which case the socket never connects.

Here's the client code:

export function useSocket(onProgress: (progress: number) => void) {
  const socket = useRef<Socket>();

  const cleanup = useCallback(() => {
    socket.current?.off('connect');
    socket.current?.off('connect_error');
    socket.current?.off('error');
    socket.current?.off(SocketMessage.PROGRESS);
    socket.current?.disconnect();
  }, []);

  const createSocket = useCallback(() => {
    socket.current = io('http://127.0.0.1:5000', { forceNew: true });
    socket.current.on('connect', () => console.log('Connected to Flask.'));
    socket.current.on('connect_error', (err: Error) => {
      console.error('CONNECTION ERROR', err);
      cleanup();
      setTimeout(() => {
        createSocket();
      }, 1000);
    });
    socket.current.on('error', (err: Error) => console.error(err));
    socket.current.on(SocketMessage.PROGRESS, onProgress);
  }, []);

  useEffect(() => {
    createSocket();
    return cleanup;
  }, [cleanup]);
}

In flask, nothing terribly interesting happening...

socketio = SocketIO(
    app, cors_allowed_origins="*", async_mode="eventlet", engineio_logger=True
)
socketio.run(app, port=5000, debug=True)

If I start the server first, then run the client, everything works as expected. If I start the client first, then the server, I continuously see a CORS error:

app_window:1 Access to XMLHttpRequest at 'http://127.0.0.1:5000/socket.io/?EIO=4&transport=polling&t=OCf9ogr' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What gives? Is this a socket.io issue, an electron cacheing issue, or a flask issue?

1 Answers

Ok I think I figured it out. Turns out port 5000 seems to be used by macOS for Focus mode. Switching to port 5001 solved the problem.

Related