美文网首页
flask socketio 轮询 日志

flask socketio 轮询 日志

作者: 你常不走的路 | 来源:发表于2019-04-30 14:08 被阅读0次

app.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/4/30 0030 13:38
# @File    : app.py
# @author  : dfkai
# @Software: PyCharm
from flask_socketio import SocketIO, emit, disconnect
from threading import Lock
from flask import Flask, render_template

app = Flask(__name__)  # static_folder="static",template_folder="templates",static_url_path="/static")
app.config['SECRET_KEY'] = 'secret!'
async_mode = None
socketio = SocketIO(app)
thread = None
thread_lock = Lock()


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


# 连接时
@socketio.on('connect', namespace='/conn_logging')
def connect():
    global thread
    print("connect")
    socketio.emit('message',
                  {'data': "hello,world!"}, namespace='/conn_logging', callback=ack)
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread)


# 关闭时
@socketio.on('disconnect_request', namespace='/conn_logging')
def disconnect_request():
    print('Client disconnected')
    disconnect()


@socketio.on("fuck", namespace="/conn_logging")
def fuck(fuck):
    print('received message: ' + str(fuck))


def ack():
    # 似乎无用
    print('message was received!')


def background_thread():
    file = r"flask.log"
    with open(file, "r") as f:
        while True:
            socketio.sleep(1)
            for line in f.readlines():
                socketio.emit('message',{'data': line}, namespace='/conn_logging', callback=ack)


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

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script>
</head>
<body>
<h1 style="margin: 0 auto ;width: 960px;text-align: center">日志管理</h1>
<div style="margin: 0 auto ;width: 960px;text-align: center">
    <input id="disconnect" type="submit" value="Disconnect">
    <input id="connect" type="submit" value="Connect">
</div>
<div id="t" style="margin: 0 auto ;width: 960px">

</div>
<script type="text/javascript">
    $(document).ready(function () {
        namespace = '/conn_logging';
        console.log(location.protocol + '//' + document.domain + ':' + location.port + namespace);
        var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);
        // 添加一个连接监听器
        // message 服务端 发送的名称
        socket.on('message', function (res) {
            console.log(res.data);
            $('#t').prepend("<p>" + res.data + "</p>");
        });
          socket.on('connect', function() {
                socket.emit('fuck', {data: 'I\'m connected!'});
        });
        $('#disconnect').click(function (event) {
            console.log("disconnect_request");
            socket.emit('disconnect_request');
            return false;
        });
    });
</script>
</body>
</html>

相关文章

网友评论

      本文标题:flask socketio 轮询 日志

      本文链接:https://www.haomeiwen.com/subject/pbxvnqtx.html