TransWikia.com

Flask Socket.io 400 error code on Azure App Services

Stack Overflow Asked on December 11, 2021

I am trying to deploy a Flask Socket.io app on Azure App Services. Locally everything works fine. However, when deploying on Azure I get a 400 code error:

WebSocket connection to
‘wss://mydomain.azurewebsites.net/socket.io/?EIO=3&transport=websocket’
failed: Error during WebSocket handshake: Unexpected response code:
400

  • websockets in Configuration/General Settings/Web
    Socket has been enabled
  • scaled up to B1 pricing tier (this seems to
    have solved the problem for some)

My server side looks like this:

from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
socketio = SocketIO(app,engineio_logger=False,log_output=False,async_mode='eventlet')

@socketio.on('btn_speaker')
def btn_agent(message):
    print(message)
    agent = message['speaker_msg']
    webchat = "speaker says: " + agent
    socketio.emit( 'webchat', {'webchat': webchat} )

@app.route('/')
def test():
    return render_template('test.html')

if __name__ == '__main__':
    socketio.run(app)

and the client:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Socket.io test</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script>
        $(document).ready(function() {
            <!-- var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port); -->
            var socket = io({transports: ['websocket']});

            $('#btn_speaker').click(function(e) {
              socket.emit( 'btn_speaker', {
                speaker_msg : $( 'input.speaker' ).val()
              } )
              $( 'input.speaker' ).val( '' ).focus()
            } )
            
            socket.on( 'webchat', function( msg ) {
                console.log( msg )
                $('#webchat').html(msg.webchat)
            })
        })
    </script>

</head>
<body>
    <textarea id="webchat" name="webchat" rows="20" cols="100"></textarea>
    <label for="speaker">text:</label>
    <input type="text" class="speaker" id="speaker" name="speaker" autocomplete="off">
    <button type="submit" id="btn_speaker">Submit speaker</button>
  </body>
</html>

requirements.txt:

eventlet
Flask-SocketIO

One Answer

Two points I had to consider in order to get this to work:

  1. The url needed to be browsed from http (instead from https)
  2. Adding --worker-class eventlet to the gunicorn startup command in Azure enabled browsing and controlling the url from different instances

Answered by Christian on December 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP