我正在尝试在 Azure 应用服务上部署 Flask Socket.io 应用。在本地一切正常。但是,在 Azure 上部署时,我收到 400 代码错误:
WebSocket connection to 'wss://mydomain.azurewebsites.net/socket.io/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 400
- 配置/常规设置/Web 中的 websockets 套接字已启用
- 扩大到 B1 定价等级(这似乎 已经解决了一些问题)
我的服务器端如下所示:
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)
和客户端:
<!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>
需求.txt:
eventlet
Flask-SocketIO
最佳答案
为了让它发挥作用,我必须考虑两点:
- 需要从 http(而不是 https)浏览网址
- 将
--worker-class eventlet
添加到 Azure 中的 Gunicorn 启动命令中,可实现从不同实例浏览和控制 URL
关于azure - Azure 应用服务上的 Flask Socket.io 400 错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63038955/