`Fail the WebSocket connection`_. .. _Fail the WebSocket connection: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7 Parameters: code: close code reason: close reason Raises: ProtocolError: If the code is
(self, code: CloseCode | int, reason: str = "")
| 430 | self.send_frame(Frame(OP_PONG, data)) |
| 431 | |
| 432 | def fail(self, code: CloseCode | int, reason: str = "") -> None: |
| 433 | """ |
| 434 | `Fail the WebSocket connection`_. |
| 435 | |
| 436 | .. _Fail the WebSocket connection: |
| 437 | https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7 |
| 438 | |
| 439 | Parameters: |
| 440 | code: close code |
| 441 | reason: close reason |
| 442 | |
| 443 | Raises: |
| 444 | ProtocolError: If the code isn't valid. |
| 445 | """ |
| 446 | # 7.1.7. Fail the WebSocket Connection |
| 447 | |
| 448 | # Send a close frame when the state is OPEN (a close frame was already |
| 449 | # sent if it's CLOSING), except when failing the connection because |
| 450 | # of an error reading from or writing to the network. |
| 451 | if self.state is OPEN: |
| 452 | if code != CloseCode.ABNORMAL_CLOSURE: |
| 453 | close = Close(code, reason) |
| 454 | data = close.serialize() |
| 455 | self.send_frame(Frame(OP_CLOSE, data)) |
| 456 | self.close_sent = close |
| 457 | # If recv_messages() raised an exception upon receiving a close |
| 458 | # frame but before echoing it, then close_rcvd is not None even |
| 459 | # though the state is OPEN. This happens when the connection is |
| 460 | # closed while receiving a fragmented message. |
| 461 | if self.close_rcvd is not None: |
| 462 | self.close_rcvd_then_sent = True |
| 463 | self.state = CLOSING |
| 464 | |
| 465 | # When failing the connection, a server closes the TCP connection |
| 466 | # without waiting for the client to complete the handshake, while a |
| 467 | # client waits for the server to close the TCP connection, possibly |
| 468 | # after sending a close frame that the client will ignore. |
| 469 | if self.side is SERVER and not self.eof_sent: |
| 470 | self.send_eof() |
| 471 | |
| 472 | # 7.1.7. Fail the WebSocket Connection "An endpoint MUST NOT continue |
| 473 | # to attempt to process data(including a responding Close frame) from |
| 474 | # the remote endpoint after being instructed to _Fail the WebSocket |
| 475 | # Connection_." |
| 476 | self.parser = self.discard() |
| 477 | next(self.parser) # start coroutine |
| 478 | |
| 479 | # Public method for getting incoming events after receiving data. |
| 480 |