The event namespace.
| 1043 | |
| 1044 | |
| 1045 | class EventNamespace(AsyncNamespace): |
| 1046 | """The event namespace.""" |
| 1047 | |
| 1048 | # The application object. |
| 1049 | app: App |
| 1050 | |
| 1051 | def __init__(self, namespace: str, app: App): |
| 1052 | """Initialize the event namespace. |
| 1053 | |
| 1054 | Args: |
| 1055 | namespace: The namespace. |
| 1056 | app: The application object. |
| 1057 | """ |
| 1058 | super().__init__(namespace) |
| 1059 | self.app = app |
| 1060 | |
| 1061 | def on_connect(self, sid, environ): |
| 1062 | """Event for when the websocket is connected. |
| 1063 | |
| 1064 | Args: |
| 1065 | sid: The Socket.IO session id. |
| 1066 | environ: The request information, including HTTP headers. |
| 1067 | """ |
| 1068 | pass |
| 1069 | |
| 1070 | def on_disconnect(self, sid): |
| 1071 | """Event for when the websocket disconnects. |
| 1072 | |
| 1073 | Args: |
| 1074 | sid: The Socket.IO session id. |
| 1075 | """ |
| 1076 | pass |
| 1077 | |
| 1078 | async def emit_update(self, update: StateUpdate, sid: str) -> None: |
| 1079 | """Emit an update to the client. |
| 1080 | |
| 1081 | Args: |
| 1082 | update: The state update to send. |
| 1083 | sid: The Socket.IO session id. |
| 1084 | """ |
| 1085 | # Creating a task prevents the update from being blocked behind other coroutines. |
| 1086 | await asyncio.create_task( |
| 1087 | self.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid) |
| 1088 | ) |
| 1089 | |
| 1090 | async def on_event(self, sid, data): |
| 1091 | """Event for receiving front-end websocket events. |
| 1092 | |
| 1093 | Args: |
| 1094 | sid: The Socket.IO session id. |
| 1095 | data: The event data. |
| 1096 | """ |
| 1097 | # Get the event. |
| 1098 | event = Event.parse_raw(data) |
| 1099 | |
| 1100 | # Get the event environment. |
| 1101 | assert self.app.sio is not None |
| 1102 | environ = self.app.sio.get_environ(sid, self.namespace) |