如何在相关请求之外发送websocket消息

时间:2019-09-12 10:17:27

标签: python-3.x websocket python-asyncio coroutine aiohttp

我建立了协程WebSocket链接,但只能在此协程内发送消息,我的问题是如何在协程之外使用当前客户端发送消息


#!/usr/bin/env python3
import  os,asyncio , threading,dotenv, aiohttp ,time,serial_asyncio,aiofiles

from aiohttp         import web, MultipartWriter

from aiohttp.web     import middleware

temple="""
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">  
    var _Connection;
    var link="ws://"+location.host+"/ws"; 
    window.onload = function ()  {setTimeout( ini_ws , 400);}

    function ini_ws()
    {
    _Connection = new WebSocket( link); 
    _Connection.onerror = function (error){document.getElementById('_link').value="Link Broken";  document.getElementById('_link').style.backgroundColor ="#FFA500"; }
    _Connection.close = function (error)  {document.getElementById('_link').value="Disconnected"; document.getElementById('_link').style.backgroundColor ="#FFE4E1";} //gray
    _Connection.onopen = function (evt)   {document.getElementById('_link').value="Connected";    document.getElementById('_link').style.backgroundColor ="#7FFF00";_Connection.send('Hello web server on Firefly' ); }
    _Connection.onmessage = function(INCOME){document.getElementById('recieve_dats').value+=INCOME.data+'\n'; }  

    setInterval(check_WS, 500); 
    }
    function check_WS(){
          if(  _Connection.readyState == 3 ) {document.getElementById('_link').style.backgroundColor ="#FFA500"; ini_ws();}
    else  if(  _Connection.readyState == 0 ) {document.getElementById('_link').style.backgroundColor ="#DC143C";  } 
    else  if(  _Connection.readyState == 2 ) {document.getElementById('_link').style.backgroundColor ="#FF0000";  }
      }
    function clear_console() {document.getElementById("recieve_dats").value=""}
    function send_command(){
        var v=document.getElementById("send_command_value").value;
        if(v) _Connection.send(v )
        document.getElementById("send_command_value").value="";
    }   
</script>
</head>
<body>
    <h2>websocket link</h2>
    <input  type="button" id="_link" onclick="ini_ws();return false;"  name=""   value="Disconnected" >
    <h2>incoming data</h2>
    <div>
        <textarea  id="recieve_dats"   > </textarea>
        <p>Console in       <button onclick="clear_console();return false;" >Clear Console</button> </p>        
    </div>
    <h2>send data to server</h2>
    <div >
        <p>Console out  <button onclick="send_command();return false;"  >Send Command</button> </p>
        <input id="send_command_value"  type="text" >            
    </div>
</body>
</html>
"""

INDEX_File=os.path.join(os.path.dirname(__file__), 'ws.html'); 
GlobalWS=GlobalRequest=None

async def websocket_handler(request):    

    print("websocket_handler");
    ws =web.WebSocketResponse()
    await ws.prepare(request)
    #request.app["websockets"].add(ws)
    GlobalWS=ws
    GlobalRequest=request
    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.TEXT:
            Income=msg.data;
            print(Income) 
            await ws.send_str("got your message website")
    #request.app["GlobalWS"]=None;#.remove(ws) 
    #request.app['websockets'].remove(ws)
    return ws

async def websockets_clear(app):
    print("websockets_clear");
    for ws in app['websockets']:
        await ws.close()
    app['websockets'].clear()


async def handle_index_page(request):
    async with aiofiles.open(INDEX_File, mode='r') as index_file:
        index_contents = await index_file.read()
    return web.Response(text=index_contents, content_type='text/html')#return web.Response(text=temple, content_type='text/html')


async def send_ws(s):
    ws = web.WebSocketResponse()    
    await ws.prepare(GlobalRequest)
    await ws.send_str(s)

async def serialRead(f):
    print("send serialRead")
    while True:
        print("sending......")
        await send_ws("helo web site ")
        await asyncio.sleep(1/f); 



async def setup_server(loop, address, port):
    app = web.Application(loop=loop)
    app.router.add_route('GET', "/", handle_index_page)
    app.router.add_route('GET', '/ws', websocket_handler)
    app["GlobalWS"] = set()
    app.on_shutdown.append(websockets_clear)
    app["threads"] = threading.Event()
    print("setup_server done");
    return await loop.create_server(app.make_handler(), address, port)

def server_begin():
    ip='0.0.0.0';port=8080
    loop = asyncio.get_event_loop()
    asyncio.run_coroutine_threadsafe(serialRead(1) , loop)
    asyncio.run_coroutine_threadsafe(setup_server(loop, ip,port ), loop)
    #coro = serial_asyncio.create_serial_connection(loop, Output, '/dev/ttyUSB0', baudrate=115200)
    print("Server ready!",ip,port)
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        print("Shutting Down!")
        loop.close()

if __name__ == '__main__':
    server_begin()

此代码停止在第send_ws(s):行进行响应 但我评论那条线,它开始起作用 我希望定期向当前客户端发送消息,但不会发送任何消息

0 个答案:

没有答案