简体   繁体   English

如何在没有客户端首先请求 python 和 flask 的情况下通过 socket-io 发送数据

[英]How can I send data though socket-io without the client requesting first with python and flask

My goal is for my Flask server to send the client data either every three seconds, or when a function is called.我的目标是让我的 Flask 服务器每三秒发送一次客户端数据,或者在调用 function 时发送客户端数据。 To do this I am using SocketIO.为此,我正在使用 SocketIO。 However based on some example code I am working with, it seems that I can only send data after a client requests something.但是,根据我正在使用的一些示例代码,我似乎只能在客户端请求某些内容后发送数据。 I don't want the client to have to 'poll' to find if there is new data, so I want the server to push it when it is ready.我不希望客户端必须“轮询”来查找是否有新数据,所以我希望服务器在准备好时推送它。

Here is what I tried so far.这是我到目前为止所尝试的。 (some of the code is unnecessary since it is based off an example) This should use socketio to push the time to the client every few seconds. (有些代码是不必要的,因为它基于一个示例)这应该使用 socketio 每隔几秒将时间推送到客户端。

HTML HTML

<!DOCTYPE HTML>
<html>
<head>
    <title>Socket-Test</title>
    <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {

            namespace = '/test';
            var socket = io(namespace);

           

            socket.on('my_response', function(msg, cb) {
                $('#log').text( $('<div/>').text(msg.data).html());
                if (cb)
                    cb();
            });
            
            
            
        });
    </script>
</head>
<body style="background-color:white;">

    <h1 style="background-color:white;">Socket</h1>
    <div id="time" ></div>
</body>
</html>

Python Python

import threading
from flask import Flask, render_template, session, copy_current_request_context,request
from flask_socketio import SocketIO, emit, disconnect
from threading import Lock
import time

async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socket_ = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()
clients = []
def update():
    time.sleep(1)
    emit('my_response',
         {'data': time.time},
         room=clients[0])
t=threading.Thread(target=update)



@socket_.on('connect')
def handle_connect():
    print('Client connected')
    clients.append(request.sid)
    t.start()


@app.route('/')
def index():
    
    return render_template('index.html', async_mode=socket_.async_mode)


@socket_.on('my_event', namespace='/test')
def test_message(message):
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': message['data'], 'count': session['receive_count']})


@socket_.on('my_broadcast_event', namespace='/test')
def test_broadcast_message(message):
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': time.time},
         broadcast=True)






socket_.run(app,port=8050)

I try to run it but it gives me the error RuntimeError: Working outside of request context.我尝试运行它,但它给了我错误RuntimeError: Working outside of request context.

I fixed my code by following this tutorial: https://www.shanelynn.ie/asynchronous-updates-to-a-webpage-with-flask-and-socket-io/我按照本教程修复了我的代码: https://www.shanelynn.ie/asynchronous-updates-to-a-webpage-with-flask-and-socket-io/

import threading
from flask import Flask, render_template, session, copy_current_request_context,request
from flask_socketio import SocketIO, emit, disconnect
from threading import Lock
import time

async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socket_ = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()

def update():
    
    time.sleep(1)
    socket_.emit('my_response',
         {'data': time.time()},
        namespace='/test')
    print("emitted")
    update()
t=threading.Thread(target=update)



@socket_.on('connect', namespace='/test')
def handle_connect():
    print('Client connected')
   
    if not t.isAlive():
        t.start()


@app.route('/')
def index():
    
    return render_template('index.html', async_mode=socket_.async_mode)


socket_.run(app,port=8070)

HTML HTML

<!DOCTYPE HTML>
<html>
<head>
    <title>Socket-Test</title>
    <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {

            namespace = '/test';
            var socket = io(namespace);

           console.log(("test"));

            socket.on('my_response', function(msg) {
                $('#time').text( $('<div/>').text(msg.data).html());
                
                console.log(msg);
            });
            
            
            
        });
    </script>
</head>
<body style="background-color:white;">

    <h1 style="background-color:white;">Socket</h1>
    <div id="time" ></div>
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使我的Flask服务器通过flask socket-IO向特定客户端发出消息 - How can I make my flask server emit messages through flask socket-IO to specific client 如何在点击事件中启动socket-io? - How can I launch socket-io on a click event? Flask Socket-IO 服务器客户端无法通信(使用 tweepy 和 twilio) - Flask Socket-IO Server Client Not Communicating (with tweepy and twilio) Flask Socket-IO 让服务器等待客户端回调 - Flask Socket-IO Having a server wait for a client callback Flask Socket-IO运行时未导入,并且导致许多问题,例如无法托管=&#39;0.0.0.0&#39; - Flask Socket-IO Runs without Importing and causing many issues like can't host='0.0.0.0' Flask Socket-IO 和 React socket.io-client,客户端不接收来自“emit”的消息 - Flask Socket-IO and React socket.io-client, client doesn't receive messages from 'emit Flask Socket-IO - 强制长轮询 - Flask Socket-IO - force long polling 未从反应 socket.io 客户端到 flask-socket.io 服务器建立连接以进行实时更新 - Connection is not getting established from react socket-io client to flask-socket-io server for real time update 如何使用 Flask Socket-io 聊天应用程序从 Google 的 Dialogflow 获得响应 - How to get a response from Google's Dialogflow with Flask Socket-io chat app 如何在 Python3 的套接字聊天室中发送和接收,而不会在打字时中断客户端? - How can I send and recieve in a socket chat room in Python3 without the client being interrupted while typing?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM