@@ -75,7 +75,7 @@ public async Task OpenAsync(string serverUri, CancellationToken cancellationToke
7575 /// A task representing the asynchronous operation of closing the WebSocket connection.
7676 /// </returns>
7777 public async Task CloseAsync ( CancellationToken cancellationToken = default ) =>
78- await webSocket . CloseAsync ( WebSocketCloseStatus . NormalClosure , String . Empty , cancellationToken ) ;
78+ await webSocket ? . CloseAsync ( WebSocketCloseStatus . NormalClosure , String . Empty , cancellationToken ) ! ;
7979
8080 private async Task ListenForMessages ( CancellationToken cancellationToken )
8181 {
@@ -96,9 +96,26 @@ private async Task ListenForMessages(CancellationToken cancellationToken)
9696 break ;
9797 }
9898
99- string message = Encoding . UTF8 . GetString ( buffer , 0 , result . Count ) ;
100- Debug . WriteLine ( $ "Received message: { message } ") ;
101- MessageReceived ? . Invoke ( this , message ) ;
99+ if ( result . EndOfMessage )
100+ {
101+ string message = Encoding . UTF8 . GetString ( buffer , 0 , result . Count ) ;
102+ MessageReceived ? . Invoke ( this , message ) ;
103+ }
104+ else
105+ {
106+ // Handle partial messages by accumulating data until EndOfMessage is true
107+ StringBuilder messageBuilder = new StringBuilder ( ) ;
108+ messageBuilder . Append ( Encoding . UTF8 . GetString ( buffer , 0 , result . Count ) ) ;
109+ while ( ! result . EndOfMessage )
110+ {
111+ result = await webSocket . ReceiveAsync (
112+ new ArraySegment < byte > ( buffer ) ,
113+ cancellationToken ) ;
114+ messageBuilder . Append ( Encoding . UTF8 . GetString ( buffer , 0 , result . Count ) ) ;
115+ }
116+ string fullMessage = messageBuilder . ToString ( ) ;
117+ MessageReceived ? . Invoke ( this , fullMessage ) ;
118+ }
102119 }
103120 }
104121 catch ( OperationCanceledException ex )
@@ -148,7 +165,6 @@ private void StartListening(CancellationToken cancellationToken)
148165 if ( ! task . IsFaulted )
149166 return ;
150167 Debug . WriteLine ( $ "Websocket listener task faulted: { task . Exception } ") ;
151- throw task . Exception ;
152168 } , TaskContinuationOptions . OnlyOnFaulted ) ;
153169 }
154170
0 commit comments