angular flask websocket not connecting

Discussão em 'Angular' iniciado por goldking HD, Outubro 21, 2024.

  1. goldking HD

    goldking HD Guest

    backend (flask):

    app = Flask(__name__)
    CORS(app)
    socketio = SocketIO(app, cors_allowed_origins="*")

    # Define a custom WebSocket event handler
    @socketio.on('connect')
    def handle_connect():
    print('WebSocket client connected')

    # Define a custom WebSocket event handler for a custom event
    @socketio.on('my_event')
    def handle_my_event(data):
    print('Received custom event: ' + data)
    emit('my_response', 'Server received: ' + data, broadcast=True)


    socketio.run(app, debug=True)


    frontend (angular)

    public connect(): Observable<any> {
    this.socket$ = new WebSocketSubject('ws://127.0.0.1:5000');
    return this.socket$.asObservable()
    }


    for some reason frontend cant connect to backend via websocket. Only thing i see in backend console is

    (8280) accepted ('127.0.0.1', 46326) 127.0.0.1 - - [12/Aug/2023 15:39:16] "GET / HTTP/1.1" 400 359 0.001002

    but when i try to connect to ws with this script it works as intended.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script>
    <script>
    var socket = io.connect('ws://127.0.0.1:5000'); // Connect to the /test namespace

    socket.on('connect', function() {
    console.log('WebSocket connected to /test namespace');
    // Send a custom event to the server after the WebSocket connection is established
    socket.emit('my_event', 'Hello, Server!');
    });

    socket.on('my_response', function(data) {
    console.log('Received response from server:', data);
    });
    </script>


    why cant angular connect to ws even though its a tutorial code

    Continue reading...

Compartilhe esta Página