Last active
July 23, 2020 08:20
-
-
Save depfryer/0ef577cdcf84709c409e04daf0e8dc17 to your computer and use it in GitHub Desktop.
customers to take action one after the other
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import json | |
import random | |
import websockets | |
from time import sleep | |
async def consumer(message): | |
if json.loads(message)['next'] == '0': | |
sleep(15) # Do what you want | |
return True | |
return False | |
async def consumer_handler(websocket, path): | |
async for message in websocket: | |
if await consumer(message): | |
return | |
async def producer_handler(websocket, path, message): | |
await websocket.send(json.dumps(message)) | |
async def hello(name): | |
uri = "ws://localhost:6789" | |
async with websockets.connect(uri) as websocket: | |
await producer_handler(websocket, '/', {'register': name}) | |
await consumer_handler(websocket, '/') | |
name = 'client' | |
asyncio.get_event_loop().run_until_complete(hello(name)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import json | |
import logging | |
import websockets | |
logging.basicConfig() | |
lock = asyncio.Lock() | |
USERS = [] | |
def JsonReady(): | |
return json.dumps({'next' : '0'}) | |
async def NotifyNext(): | |
if USERS: # asyncio.wait doesn't accept an empty list | |
async with lock: | |
message = JsonReady() | |
v = USERS[0] | |
await asyncio.wait([v.send(message)]) | |
async def NotifyAll(): | |
if USERS: # asyncio.wait doesn't accept an empty list | |
message = JsonReady() | |
await asyncio.wait([user.send(message)for user in USERS]) | |
async def register(websocket): | |
USERS.append(websocket) | |
if len(USERS) <= 1: | |
await NotifyNext() | |
async def unregister(websocket): | |
USERS.remove(websocket) | |
await NotifyNext() | |
async def Waiter(websocket, path): | |
# register(websocket) sends user_event() to websocket | |
await register(websocket) | |
try: | |
async for message in websocket: | |
data = json.loads(message) | |
print(data['register']) | |
finally: | |
await unregister(websocket) | |
start_server = websockets.serve(Waiter, "localhost", 6789) | |
asyncio.get_event_loop().run_until_complete(start_server) | |
asyncio.get_event_loop().run_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment