python websockets服务端程序示例(带定时推送功能)

xingyun86 8月前 258

python websockets服务端程序示例(带定时推送功能)

示例一:

#!/usr/bin/env python
import asyncio
import threading
from websockets.server import serve
bOk=False
async def push_data(wssp):
    global bOk
    while True:
        try:
            if bOk == True:
                print('push')
                await wssp.send('push')
            await asyncio.sleep(0.05)
        except:
            print('exit')
            break

async def do(wssp,path):
    print('enter do')
    asyncio.create_task(push_data(wssp)
    async for msg in wssp:
        if msg=='123':
            await wssp.send(msg)
        elif msg=='456':
            await wssp.send(msg)
            global bOk
            if bOk == False:
                bOk=True
        elif msg == '567':
            bOk=False
            await wssp.send(msg)

async def main():
    async with serve(do, "127.0.0.1", 8765):
        await asyncio.Future()  # run forever
asyncio.run(main())

示例二:

#!/usr/bin/env python
import asyncio
import threading
import websockets

bOk=False
async def push_data(wssp):
    global bOk
    while True:
        try:
            if bOk == True:
                print('push')
                await wssp.send('push')
            await asyncio.sleep(0.05)
        except:
            print('exit')
            break
async def recv_msg(wssp):
    global bOk
    while True:
        msg = await wssp.recv()
        if msg=='123':
            print(bOk)
            await wssp.send(msg)
        elif msg=='456':
            await wssp.send(msg)
            print(bOk)
            if bOk == False:
                bOk=True
            print(bOk)
        elif msg == '567':
            print(bOk)
            bOk=False
            await wssp.send(msg)
async def do(wssp,path):
    print('enter do')
    asyncio.create_task(push_data(wssp))
    wait recv_msg(wssp)

start_server = websockets.serve(do, "127.0.0.1", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()


×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回