3838CONN_TIMEOUT = 60 # default connect & disconnect timeout, in seconds
3939MESSAGE_QUEUE_SIZE = 1
4040MAX_MESSAGE_SIZE = 2 ** 20 # 1 MiB
41- RECEIVE_BYTES = 4 * 2 ** 10 # 4 KiB
41+ DEFAULT_RECEIVE_BYTES = 4 * 2 ** 10 # 4 KiB
4242logger = logging .getLogger ('trio-websocket' )
4343
4444
@@ -687,7 +687,8 @@ class WebSocketConnection(trio.abc.AsyncResource):
687687 def __init__ (self , stream , ws_connection , * , host = None , path = None ,
688688 client_subprotocols = None , client_extra_headers = None ,
689689 message_queue_size = MESSAGE_QUEUE_SIZE ,
690- max_message_size = MAX_MESSAGE_SIZE ):
690+ max_message_size = MAX_MESSAGE_SIZE ,
691+ receive_buffer_size = DEFAULT_RECEIVE_BYTES ):
691692 '''
692693 Constructor.
693694
@@ -713,6 +714,9 @@ def __init__(self, stream, ws_connection, *, host=None, path=None,
713714 :param int max_message_size: The maximum message size as measured by
714715 ``len()``. If a message is received that is larger than this size,
715716 then the connection is closed with code 1009 (Message Too Big).
717+ :param Optional[int] receive_buffer_size: The buffer size we use to
718+ receive messages internally. None to let trio choose. Defaults
719+ to 4 KiB.
716720 '''
717721 # NOTE: The implementation uses _close_reason for more than an advisory
718722 # purpose. It's critical internal state, indicating when the
@@ -725,6 +729,7 @@ def __init__(self, stream, ws_connection, *, host=None, path=None,
725729 self ._message_size = 0
726730 self ._message_parts : List [Union [bytes , str ]] = []
727731 self ._max_message_size = max_message_size
732+ self ._receive_buffer_size = receive_buffer_size
728733 self ._reader_running = True
729734 if ws_connection .client :
730735 self ._initial_request : Optional [Request ] = Request (host = host , target = path ,
@@ -1232,7 +1237,7 @@ async def _reader_task(self):
12321237
12331238 # Get network data.
12341239 try :
1235- data = await self ._stream .receive_some (RECEIVE_BYTES )
1240+ data = await self ._stream .receive_some (self . _receive_buffer_size )
12361241 except (trio .BrokenResourceError , trio .ClosedResourceError ):
12371242 await self ._abort_web_socket ()
12381243 break
0 commit comments