python - 使用flask-socketio实现tail log的问题
高洛峰
高洛峰 2017-04-18 10:24:43
0
0
846

问题是前端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
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

répondre à tous(0)
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal