为什么asyncio.sleep()阻止我的WebSocket从服务器接收输入?

问题描述 投票:0回答:2

我想建立一个库,它允许在一个从浏览器应用程序中的DOM蟒蛇控制。

目前我正在试图不将信息发送到DOM,但请求,然后从它收到的一条信息。

下面这个例子中被配置为申请(在此情况下的ID)有关给定元素的属性。

该设置是相当简单的。发送请求时,反复检查了该请求的ID注册为一个注册表中的非无值,使用asyncio.sleep停止检查程序和控制释放返回到接收器,因此它可以,很好,收到。

这,顺便说一句,是(据说)工作实现的几乎相同的拷贝。搜索Python的索菲桂在谷歌,如果你很好奇。

asyncio.sleep似乎暂停整个过程,而不是用于信号的接收控制权返回给网络服务器。有没有用我的理解,我的实现,或两者有问题吗?

蟒蛇

import os, sys, asyncio, websockets, json, time

websocket_global = None
requests = {}

event_loop = asyncio.get_event_loop()

def quit():

    os.system( 'kill $(lsof -t -i :9000)' )

async def load( websocket ):

    await get_attribute( websocket, 'head', 'id' )

async def receive( websocket, path ):

    try: 
        async for input in websocket: await handle_input( websocket, input )

    except Exception as e: os.system( 'kill $(lsof -t -i :9000)' )

async def handle_input( websocket, input ):

    message = json.loads( input )

    if message[ 'message' ] == 'quit': quit()

    if message[ 'message' ] == 'load': await load( websocket )

    if message[ 'message' ] == 'response': receive_response( message )

def transmit( websocket, message ):

    asyncio.run_coroutine_threadsafe( websocket.send( message ), event_loop )

def receive_response( message ):

    responses[ message[ 'message_id' ] ] = message[ 'value' ]

async def wait_for_response( request_id ):

    while requests[ request_id ] == None: await asyncio.sleep( .01 )

    print( requests[ request_id ] ) ###<------------- The above asyncio.sleep is blocking the rest of the progrem
                                ###preventing the receive function from firing. Isn't sleep supposed to
                                ###let the program continue?

 async def get_attribute( websocket, selector, attr ):

    request_id = time.time(); requests[ request_id ] = None

    transmit( websocket, json.dumps( { 'message': 'get_attribute', 'request_id': request_id, 'selector': selector, 'attr': attr } ) )

    response = await wait_for_response( request_id )

    return response

quit()

html_path = os.path.dirname( os.path.realpath( __file__ ) )
html_path = html_path.replace( ' ', '\ ' )
html_path = html_path + '/main.html'

os.system( 'open -a Safari ' + html_path )

start_server = websockets.serve( receive, '0.0.0.0', 9000 )
event_loop.run_until_complete( start_server )
event_loop.run_forever()

JavaScript的

是插座= NULL;

function get_attribute( message ) {

    var response = {};
    var target_element = document.getElementById( message[ 'selector' ] );

    if ( target_element == null ) {
        response = { 'message': 'response', 'request_id': message[ 'request_id' ], 'response': 'Element not Found' };
    }

    if ( target_element != null && target_element.getAttribute( message[ 'attr' ] ) == null ) {
        response = { 'message': 'response', 'request_id': message[ 'request_id' ], 'response': 'Attribute not Found' };
    }

    if ( target_element != null && target_element.getAttribute( message[ 'attr' ] ) != null ) {
        var target_attribute = target_element.getAttribute( message[ 'attr' ] )
        response = { 'message': 'response', 'request_id': message[ 'request_id' ], 'response': target_attribute };
    }

    socket.send( JSON.stringify( response ) );

}

function handle_input( message ) {

    if ( message[ 'message' ] == 'get_attribute' ) { get_attribute( message ) }

}

window.onload = function(event) {

    socket = new WebSocket( 'ws://0.0.0.0:9000' );

    socket.onopen = function( event ) {
        socket.send( JSON.stringify( { 'message': 'load' } ) )
        setInterval( function () { socket.send( JSON.stringify( { 'message': 'tick' } ) ) }, 1000 )
    }

    socket.onmessage = function( event ) {
        handle_input( JSON.parse( event.data ) )
    }

}

window.onbeforeunload = function( event ) {
    socket.send( JSON.stringify( { 'message': 'quit' } ) )
}

HTML

<!DOCTYPE html>
<html>
<head id="head">
    <title>Test</title>
    <script type="text/javascript" src="handler.js"></script>
</head>
<body id="body">

</body>
</html>

道歉差拼写或语法错误。我的键盘已经开始去已成为不合作的各种按键。

python-3.x websocket sleep python-asyncio
2个回答
0
投票

什么是设置requests[request_id]因此while循环将永远不会退出。你也应该避免全局变量。


0
投票
if message[ 'message' ] == 'response': receive_response( message )

def receive_response( message ):

    responses[ message[ 'message_id' ] ] = message[ 'value' ]

虽然解决了它。

receive_response while循环,我把:

message = await pyscript.websocket.recv();

handle_response( json.loads( message ) );

并创建了功能:

def handle_response( input ):

    if input[ 'message' ] == 'response': receive_response( input );

我没有受过正规教育,但这样我问,你为什么看不惯全局?他们一直担任我不够好。

© www.soinside.com 2019 - 2024. All rights reserved.