精华内容
下载资源
问答
  • python-socketio 是 Socket.IO 服务器的 Python 实现
  • I am in the situation where I receive a message from the ... Within the function that handles that request (@socketio.on) I want to call a function where some heavy work is done. This should not r...

    I am in the situation where I receive a message from the client. Within the function that handles that request (@socketio.on) I want to call a function where some heavy work is done. This should not result in blocking the main thread and the client is thought to be informed once the work is done. Thus I start a new thread.

    Now I encounter a really strange behavior:

    The message never reaches the client. However, the code reaches that particular spot where the message is sent.

    Even more surprising is the fact that if there is nothing happening in the thread except for the message being sent to the client then the answer actually finds its way to the client.

    To sum it up:

    If something computationally intensive happens before the message is sent it is not being delivered, otherwise it is.

    Like it is said here and here, sending messages from a thread to the clients is not a problem at all:

    In all the examples shown until this point the server responds to an event sent by the client. But for some applications, the server needs to be the originator of a message. This can be useful to send notifications to clients of events that originated in the server, for example in a background thread.

    Here is a sample code. When removing the commenting sharps (#) the message ('foo from thread') does not find its way to the client, otherwise it does.

    from flask import Flask

    from flask.ext.socketio import SocketIO, emit

    app = Flask(__name__)

    socketio = SocketIO(app)

    from threading import Thread

    import time

    @socketio.on('client command')

    def response(data):

    thread = Thread(target = testThreadFunction)

    thread.daemon = True

    thread.start()

    emit('client response', ['foo'])

    def testThreadFunction():

    # time.sleep(1)

    socketio.emit('client response', ['foo from thread'])

    socketio.run(app)

    I am using Python 3.4.3, Flask 0.10.1, flask-socketio1.2, eventlet 0.17.4.

    This sample can be copied and pasted in a .py file and the behavior can be instantly reproduced.

    Can somebody explain this strange behavior?

    Update

    It seems to be a bug of eventlet. If I do:

    socketio = SocketIO(app, async_mode='threading')

    It forces the application not to use eventlet although it is installed.

    However, this is not an applicable solution for me as using 'threading' as async_mode refuses to accept binary data. Every time I send some binary data from the client to the server it says:

    WebSocket transport not available. Install eventlet or gevent and gevent-websocket for improved performance.

    The third option, using gevent as the async_mode does not work for me as well as gevent does not have support for python 3 yet.

    So any other suggestions?

    解决方案

    I managed to resolve the issue by monkeypatching several Python functions which causes Python to use the eventlet functions instead of the native ones. This way background threads work fine with eventlet.

    展开全文
  • python socketio 服务器编程

    千次阅读 2020-01-13 16:43:59
    项目源码:https://github.com/yicaifenchen8/socketio.git 1.配置密钥等 app = Flask(__name__) app.config['SECRET_KEY'] ...socketio = SocketIO() socketio.init_app(app) thread = None thread_lock = Lo...

    项目源码:https://github.com/yicaifenchen8/socketio.git

    1.配置密钥等

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    
    socketio = SocketIO()
    socketio.init_app(app)
    
    
    thread = None
    
    thread_lock = Lock()

    2.线程创建

    # 后台线程 产生数据,即刻推送至前端
    
    def background_thread():
        count = 0
    
        while True:
            socketio.sleep(5)
    
            count += 1
    
            t = time.strftime('%M:%S', time.localtime())
    
            # 获取系统时间(只取分:秒)
    
            cpus = psutil.cpu_percent(interval=None, percpu=True)
    
            # 获取系统cpu使用率 non-blocking
    
            socketio.emit('server_response',
    
                          {'data': [t, cpus], 'count': count},
    
                          namespace='/test')
    
            socketio.emit('messageEventNew',
    
                          {'encryptkey':'key'},
    
                          namespace='/test')
    
            # 注意:这里不需要客户端连接的上下文,默认 broadcast = True

    3.消息监听

    @app.route('/')
    def index():
        return render_template('index.html', async_mode=socketio.async_mode)
    
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        print('connect')
        global thread
    
        with thread_lock:
            if thread is None:
                thread = socketio.start_background_task(target=background_thread)
    
    @socketio.on('onMessageArrive', namespace='/test')
    def test_connect():
        print('onMessageArrive')

    4.运行

    if __name__ == '__main__':
        # 只能点击main运行,flask项目修改不了host,新增pure项目拷贝代码即可
        socketio.run(app, host='10.10.9.74', port=5000, debug=True)

    项目源码:https://github.com/yicaifenchen8/socketio.git

     

    展开全文
  • from socketIO_client import SocketIO socketio = SocketIO('http://192.168.1.12:6688') socketio.on('disconnect',sioConnect) socketio.on('connect',sioDisconnect) def sioDisconnect(*args): log('socketio...

    客户端

    from socketIO_client import SocketIO
    socketio = SocketIO('http://192.168.1.12:6688')
    socketio.on('disconnect',sioConnect)
    socketio.on('connect',sioDisconnect)
    
    def sioDisconnect(
    展开全文
  • I have the following situation:I receive a request on a socketio server. I answer it (socket.emit(..)) and then start something with heavy computation load in another thread.If the heavy computation i...

    I have the following situation:

    I receive a request on a socketio server. I answer it (socket.emit(..)) and then start something with heavy computation load in another thread.

    If the heavy computation is caused by subprocess.Popen (using subprocess.PIPE) it totally blocks every incoming request as long as it is being executed although it happens in a separate thread.

    No problem - in this thread it was suggested to asynchronously read the result of the subprocess with a buffer size of 1 so that between these reads other threads have the chance to do something. Unfortunately this did not help for me.

    I also already monkeypatched eventlet and that works fine - as long as I don't use subprocess.Popen with subprocess.PIPE in the thread.

    In this code sample you can see that it only happens using subprocess.Popen with subprocess.PIPE. When uncommenting #functionWithSimulatedHeavyLoad() and instead comment functionWithHeavyLoad() everything works like charm.

    from flask import Flask

    from flask.ext.socketio import SocketIO, emit

    import eventlet

    eventlet.monkey_patch()

    app = Flask(__name__)

    socketio = SocketIO(app)

    import time

    from threading import Thread

    @socketio.on('client command')

    def response(data, type = None, nonce = None):

    socketio.emit('client response', ['foo'])

    thread = Thread(target = testThreadFunction)

    thread.daemon = True

    thread.start()

    def testThreadFunction():

    #functionWithSimulatedHeavyLoad()

    functionWithHeavyLoad()

    def functionWithSimulatedHeavyLoad():

    time.sleep(5)

    def functionWithHeavyLoad():

    from datetime import datetime

    import subprocess

    import sys

    from queue import Queue, Empty

    ON_POSIX = 'posix' in sys.builtin_module_names

    def enqueueOutput(out, queue):

    for line in iter(out.readline, b''):

    if line == '':

    break

    queue.put(line)

    out.close()

    # just anything that takes long to be computed

    shellCommand = 'find / test'

    p = subprocess.Popen(shellCommand, universal_newlines=True, shell=True, stdout=subprocess.PIPE, bufsize=1, close_fds=ON_POSIX)

    q = Queue()

    t = Thread(target = enqueueOutput, args = (p.stdout, q))

    t.daemon = True

    t.start()

    t.join()

    text = ''

    while True:

    try:

    line = q.get_nowait()

    text += line

    print(line)

    except Empty:

    break

    socketio.emit('client response', {'text': text})

    socketio.run(app)

    The client receives the message 'foo' after the blocking work in the functionWithHeavyLoad() function is completed. It should receive the message earlier, though.

    This sample can be copied and pasted in a .py file and the behavior can be instantly reproduced.

    I am using Python 3.4.3, Flask 0.10.1, flask-socketio1.2, eventlet 0.17.4

    Update

    If I put this into the functionWithHeavyLoad function it actually works and everything's fine:

    import shlex

    shellCommand = shlex.split('find / test')

    popen = subprocess.Popen(shellCommand, stdout=subprocess.PIPE)

    lines_iterator = iter(popen.stdout.readline, b"")

    for line in lines_iterator:

    print(line)

    eventlet.sleep()

    The problem is: I used find for heavy load in order to make the sample for you more easily reproducable. However, in my code I actually use tesseract "{0}" stdout -l deu as the sell command. This (unlike find) still blocks everything. Is this rather a tesseract issue than eventlet? But still: how can this block if it happens in a separate thread where it reads line by line with context switch when find does not block?

    解决方案

    Thanks to this question I learned something new today. Eventlet does offer a greenlet friendly version of subprocess and its functions, but for some odd reason it does not monkey patch this module in the standard library.

    Looking at the eventlet patcher, the modules that are patched are os, select, socket, thread, time, MySQLdb, builtins and psycopg2. There is absolutely no reference to subprocess in the patcher.

    The good news is that I was able to work with Popen() in an application very similar to yours, after I replaced:

    import subprocess

    with:

    from eventlet.green import subprocess

    But note that the currently released version of eventlet (0.17.4) does not support the universal_newlines option in Popen, you will get an error if you use it. Support for this option is in master (here is the commit that added the option). You will either have to remove that option from your call, or else install the master branch of eventlet direct from github.

    展开全文
  • python-socketio 是 Socket.IO 服务器的 Python 实现 python-socketio Socket.IO 实时客户端和服务器的 Python 实现。 资源文档 PyPI 更改日志问题? 查看其他人在 Stack Overflow 上提出的问题,或提出您自己的...
  • python-socketioPython Socket.IO服务器和客户端
  • socketio_examples socketio的使用案例,包含python-socketio
  • 背景描述 最近开发的项目需要用到 socket-io,于是网上找了一段 socket-io 的 server 和 client 代码,把这两份代码都...socketio.exceptions.connectionerror: unexpected status code 400 in server response 在网上
  • python-socketio Python implementation of the Socket.IO realtime client and server. Version compatibility The Socket.IO protocol has been through a number of revisions, and some of these ...
  • **尝试过使用python-socketio包进行连接/数据收发** 代码示例: ```python from flask import Flask sio = socketio.Server(async_mode='threading', cors_allowed_origins='*', engineio_logger=True) ...
  • if __name__ == '__main__': sio.connect(server) 错误: Attempting polling connection to http://192.168.1.166:2120/socket.io/?transport=polling&EIO=4 Traceback (most recent call last): File "E:/python_...
  • <p><img alt="" height="375" src="https://img-ask.csdnimg.cn/upload/1621214990113.png" width="664" /></p>   以上是代码 <p><img alt="" height="499... <p>python-socketio版本是5.1.0 <p>python版本3.7</p>
  • python_socketio_vote.zip

    2019-11-26 15:07:40
    基于flask框架实现的一个简单的及时投票网站小例子,用到了flask的第三方插件:socketio、SQLAlchemy。参考学习。
  • 但是在执行完popen后在调用socketio.emit就没有反应了 后端flask如下 ``` @socketio.on('work') def towork(): t=threading.Thread(target=test) t.start() def test(): socketio.emit('listen',...
  • 在使用fastapi进行开发中,使用python-socketio作为socketi库,前端项目使用vue开发,配合socket.io-client作为client端。 我的python-socketio版本号为4.6.0 前端socket.io-client我默认安装的最新的,此时最新的是...
  • 在使用python-socketio中,出现"KeyError: 'CONDA_PREFIX'错误
  •  File "/home/tianyxu/.local/lib/python3.6/site-packages/urllib3/contrib/pyopenssl.py", line 485, in wrap_socket  cnx.do_handshake()  File "/home/tianyxu/.local/lib/python3.6/site-packages/OpenSSL...
  • vue+python flask_socketio 报400错误 跨域 PIL 往图片上写入中文报错 UnicodeEncodeError: ‘latin-1’ codec can’t encode characters in position 问题描述: 前端vue 后端 python flask_socketio 报400错误 ...
  • 多个socketio服务器通过消息队列来沟通之间的客户端sid。若发现该sid在自己的连接中。就由该进程处理发送给其下面连接的客户端详细的可以看这里socket.io要实现多进程以及广播,房间等功能,势必需要接入一个redis之...
  • pythonsocketio,Access-Control-Allow-Origin跨域问题,这个帖子真真帮助了我 欢迎使用Markdown编辑器 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细...
  • python2安装flask-socketIO

    2021-08-28 20:49:13
    尝试安装flask-socketio,直接使用命令 pip install flask-...=0.21.0 (from python-socketio>=5.0.2->flask-socketio) 因此尝试安装一下低版本, 命令:pip install "Flask-SocketIO<5.0.0" 安装的时

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,761
精华内容 704
关键字:

pythonsocketio

python 订阅