Send a `Close frame`_. .. _Close frame: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.1 Parameters: code: close code. reason: close reason. Raises: ProtocolError: If the code isn't valid or if a reason is
(self, code: CloseCode | int | None = None, reason: str = "")
| 362 | self.send_frame(Frame(OP_BINARY, data, fin)) |
| 363 | |
| 364 | def send_close(self, code: CloseCode | int | None = None, reason: str = "") -> None: |
| 365 | """ |
| 366 | Send a `Close frame`_. |
| 367 | |
| 368 | .. _Close frame: |
| 369 | https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.1 |
| 370 | |
| 371 | Parameters: |
| 372 | code: close code. |
| 373 | reason: close reason. |
| 374 | |
| 375 | Raises: |
| 376 | ProtocolError: If the code isn't valid or if a reason is provided |
| 377 | without a code. |
| 378 | |
| 379 | """ |
| 380 | # While RFC 6455 doesn't rule out sending more than one close Frame, |
| 381 | # websockets is conservative in what it sends and doesn't allow that. |
| 382 | if self._state is not OPEN: |
| 383 | raise InvalidState(f"connection is {self.state.name.lower()}") |
| 384 | if code is None: |
| 385 | if reason != "": |
| 386 | raise ProtocolError("cannot send a reason without a code") |
| 387 | close = Close(CloseCode.NO_STATUS_RCVD, "") |
| 388 | data = b"" |
| 389 | else: |
| 390 | close = Close(code, reason) |
| 391 | data = close.serialize() |
| 392 | # 7.1.3. The WebSocket Closing Handshake is Started |
| 393 | self.send_frame(Frame(OP_CLOSE, data)) |
| 394 | # Since the state is OPEN, no close frame was received yet. |
| 395 | # As a consequence, self.close_rcvd_then_sent remains None. |
| 396 | assert self.close_rcvd is None |
| 397 | self.close_sent = close |
| 398 | self.state = CLOSING |
| 399 | |
| 400 | def send_ping(self, data: BytesLike) -> None: |
| 401 | """ |