flask 使用websocket和后端通信

python代码:

from threading import Lock
from flask import Flask,render_template
from flask_socketio import SocketIO, emit
from socket import *
import threading
import json
from time import sleep,ctime

async_mode = None

app = Flask(__name__)
app.debug = False
app.threaded=True
app.config['SECRET_KEY'] = 'secret!'

thread = None
thread_lock = Lock()

count = 0
tcpdict = {}

filename = 'car.json'

def read_json():
    with open(filename) as pf:
        numbers = json.load(pf)
        print(numbers)
        return numbers


socketio = SocketIO(app,async_mode=async_mode)

def background_thread():
    count = 0
    while True:
        socketio.sleep(2)
        data=read_json()
        socketio.emit('server_response', data,
                          namespace='/test')


@app.route('/')
def index():
    # return "hello flask test"
    return render_template('index.html',async_mode=socketio.async_mode)

@socketio.on('connect',namespace='/test')
def test_connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread)

def main():
    socketio.run(app)

if __name__ == '__main__':
    main()

前端代码:

<html>
<body>

<script>
        // 建立socket连接,等待服务器“推送”数据,用回调函数更新图表
        $(document).ready(function () {
            namespace = '/test';
            var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);

            socket.on('server_response', function (res) {
                console.log(res)
                console.log(res.workStatusNow)
                console.log(res.gps_height)
            });

        });
</script>
</body>
</html>


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值