使用flask-socketio实现tail log的问题

问题是前端http://127.0.0.1:5000/页面报错是:

socket.io.js:7370 WebSocket connection to 'ws://127.0.0.1:5000/socket.io/?EIO=3&transport=websocket&sid=fae5fcea9cd444a0ad4edae4ec3c5edc' failed: Error during WebSocket handshake: Unexpected response code: 400

下面是详细的现场:

app.py
def background_stuff():
    """ Let's do it a bit cleaner """
    socketio.emit('message', {'data': 'This is data', 'time': open('job.log').readlines()}, namespace='/test')


@app.route('/')
def index():
    global thread
    if thread is None:
        thread = Thread(target=background_stuff)
        thread.start()
    return render_template('index.html')

前端templates/index.html

<script type="text/javascript" src='https://cdnjs.cloudflare.com/...',></script>
<script type="text/javascript" charset="utf-8">

$(document).ready(function(){
    namespace = '/test'; // change to an empty string to use the global namespace
    // the socket.io documentation recommends sending an explicit package upon connection
    // this is specially important when using the global namespace
    var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);

    socket.on('connect', function(msg) {
        socket.emit('my event', {data: 'connect'});
    });

    socket.on('message', function(msg){
        console.log(msg.time);
        $('#test').html('<p>' + msg.time + '</p>');
    });

});

</script>

启动方式:


gunicorn --worker-class=gevent -w 4 -b 127.0.0.1:5000 app:app
阅读 4.4k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题