forked from APAP-ICT/APAP-ai
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
51 additions
and
28 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,31 @@ | ||
from typing import List | ||
from collections import defaultdict | ||
|
||
from starlette.websockets import WebSocket, WebSocketDisconnect | ||
|
||
|
||
class ConnectionManager: | ||
def __init__(self): | ||
self.publisher = None | ||
self.subscribers: List[WebSocket] = [] | ||
self.publishers: defaultdict = defaultdict(WebSocket) | ||
self.subscribers: defaultdict = defaultdict(list) | ||
|
||
async def connect(self, websocket: WebSocket): | ||
async def connect(self, location_name: str, websocket: WebSocket): | ||
await websocket.accept() | ||
self.publisher = websocket | ||
self.publishers[location_name] = websocket | ||
|
||
def disconnect(self): | ||
self.publisher = None | ||
def disconnect(self, location_name: str): | ||
del self.publishers[location_name] | ||
|
||
async def subscribe(self, websocket: WebSocket): | ||
async def subscribe(self, location_name: str, websocket: WebSocket): | ||
await websocket.accept() | ||
self.subscribers.append(websocket) | ||
self.subscribers[location_name].append(websocket) | ||
|
||
def unsubscribe(self, websocket: WebSocket): | ||
self.subscribers.remove(websocket) | ||
def unsubscribe(self, location_name: str, websocket: WebSocket): | ||
self.subscribers[location_name].remove(websocket) | ||
|
||
async def broadcast(self, message: bytes): | ||
for subscriber in self.subscribers: | ||
async def broadcast(self, location_name: str, message: bytes): | ||
subscribers_by_location = self.subscribers[location_name] | ||
for subscriber in subscribers_by_location: | ||
try: | ||
await subscriber.send_bytes(message) | ||
except WebSocketDisconnect: | ||
self.unsubscribe(subscriber) | ||
self.unsubscribe(location_name, subscriber) |
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