remote-close_wsh.py (1355B)
1 # Copyright (c) 2024 The Chromium Authors. All rights reserved. 2 # Use of this source code is governed by a BSD-style license that can be 3 # found in the LICENSE file. 4 5 """ 6 Perform a server-initiated close according to the parameters passed in the 7 query string. Supported parameters: 8 9 * code=INT: The close code to send in the close frame. If omitted the Close 10 frame will have an empty body. 11 12 * reason=TEXT: The reason to be sent in the close frame. Only sent if `code` is 13 set. 14 15 * abrupt=1: Close the connection without sending a Close frame. 16 17 Example: /remote-close?code=1000&reason=Done 18 19 """ 20 21 import urllib 22 23 from pywebsocket3.handshake import AbortedByUserException 24 25 26 def web_socket_do_extra_handshake(request): 27 pass 28 29 30 def web_socket_transfer_data(request): 31 parts = urllib.parse.urlsplit(request.uri) 32 parameters = urllib.parse.parse_qs(parts.query) 33 if 'abrupt' in parameters: 34 # Send a ping frame to make sure this isn't misinterpreted as a 35 # handshake failure. 36 request.ws_stream.send_ping('ping') 37 # Rudely close the connection. 38 raise AbortedByUserException('Abort the connection') 39 code = None 40 reason = None 41 if 'code' in parameters: 42 code = int(parameters['code'][0]) 43 reason = parameters.get('reason', [''])[0] 44 request.ws_stream.close_connection(code, reason)