miguelgrinberg / flask-sock

Modern WebSocket support for Flask.
MIT License
272 stars 24 forks source link

Can't connect to websocket on Chrome #56

Closed osintalex closed 1 year ago

osintalex commented 1 year ago

Hey, I'm running a very simple app to test this extension out. Working great on Firefox but I can't open the connection in Chrome.

Wondering if I need to do something to allow connections to localhost in Chrome? It looks like that may be the case based off this post. Not getting anything useful from the error handler in the frontend either.

This is my Flask code:

from flask import Flask, current_app
from flask_sock import Sock
import logging
from time import sleep

app = Flask(__name__)
sock = Sock(app)
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)

@sock.route('/echo')
def echo(sock):
    current_app.logger.info("started websocket connection")
    sock.send('init')

I'm running with gunicorn -b 127.0.0.1:5000 --workers 4 --threads 100 --log-level=debug main:app.

Then this is my React code:

import logo from "./logo.svg";
import "./App.css";
import { useEffect } from "react";

function App() {
  useEffect(() => {
    const socket = new WebSocket("ws://localhost:5000/echo");
    socket.onerror = (event) => {
      console.log("WebSocket error: ", event);
    };
    socketConnection.current = socket;
    socket.onopen = (_event) => {
      socket.send("Hello Server!");
    };

    socket.onmessage = (event) => {
      console.log("Message from server ", event.data);
    };

    socket.onclose = (_event) => {
      console.log("Closing websocket connection");
    };

    // required otherwise you get duplicate connections from React in dev mode
    // see https://github.com/facebook/create-react-app/issues/10387
    // this also means you get an error you can ignore in local dev that the page is reloading
    // when it tries to init the connection
    return () => socket.close();
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p onClick={stopStreamOnClick}>Click to stop</p>
        <p onClick={keepStreamingOnClick}>Click to keep going</p>

        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;
osintalex commented 1 year ago

Finally figured this out after much exasperation. I had to change client side url to "ws://127.0.0.1:5000/echo" not "ws://localhost:5000/echo".

Then this worked fine in Chrome and Safari. Previously it wasn't working in Chrome or Safari.