Send ASGI websocket messages, ensuring valid state transitions.
(self, message: Message)
| 63 | raise WebSocketDisconnected('Cannot call "receive" once a disconnect message has been received.') |
| 64 | |
| 65 | async def send(self, message: Message) -> None: |
| 66 | """ |
| 67 | Send ASGI websocket messages, ensuring valid state transitions. |
| 68 | """ |
| 69 | if self.application_state == WebSocketState.CONNECTING: |
| 70 | message_type = message["type"] |
| 71 | if message_type not in {"websocket.accept", "websocket.close", "websocket.http.response.start"}: |
| 72 | raise RuntimeError( |
| 73 | 'Expected ASGI message "websocket.accept", "websocket.close" or "websocket.http.response.start", ' |
| 74 | f"but got {message_type!r}" |
| 75 | ) |
| 76 | if message_type == "websocket.close": |
| 77 | self.application_state = WebSocketState.DISCONNECTED |
| 78 | elif message_type == "websocket.http.response.start": |
| 79 | self.application_state = WebSocketState.RESPONSE |
| 80 | else: |
| 81 | self.application_state = WebSocketState.CONNECTED |
| 82 | await self._send(message) |
| 83 | elif self.application_state == WebSocketState.CONNECTED: |
| 84 | message_type = message["type"] |
| 85 | if message_type not in {"websocket.send", "websocket.close"}: |
| 86 | raise RuntimeError( |
| 87 | f'Expected ASGI message "websocket.send" or "websocket.close", but got {message_type!r}' |
| 88 | ) |
| 89 | if message_type == "websocket.close": |
| 90 | self.application_state = WebSocketState.DISCONNECTED |
| 91 | try: |
| 92 | await self._send(message) |
| 93 | except OSError: |
| 94 | self.application_state = WebSocketState.DISCONNECTED |
| 95 | raise WebSocketDisconnect(code=1006) |
| 96 | elif self.application_state == WebSocketState.RESPONSE: |
| 97 | message_type = message["type"] |
| 98 | if message_type != "websocket.http.response.body": |
| 99 | raise RuntimeError(f'Expected ASGI message "websocket.http.response.body", but got {message_type!r}') |
| 100 | if not message.get("more_body", False): |
| 101 | self.application_state = WebSocketState.DISCONNECTED |
| 102 | await self._send(message) |
| 103 | else: |
| 104 | raise WebSocketDisconnected('Cannot call "send" once a close message has been sent.') |
| 105 | |
| 106 | async def accept( |
| 107 | self, |