@@ -75,7 +75,7 @@ public async Task OpenAsync(string serverUri, CancellationToken cancellationToke
75
75
/// A task representing the asynchronous operation of closing the WebSocket connection.
76
76
/// </returns>
77
77
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 ) ! ;
79
79
80
80
private async Task ListenForMessages ( CancellationToken cancellationToken )
81
81
{
@@ -96,9 +96,26 @@ private async Task ListenForMessages(CancellationToken cancellationToken)
96
96
break ;
97
97
}
98
98
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
+ }
102
119
}
103
120
}
104
121
catch ( OperationCanceledException ex )
@@ -148,7 +165,6 @@ private void StartListening(CancellationToken cancellationToken)
148
165
if ( ! task . IsFaulted )
149
166
return ;
150
167
Debug . WriteLine ( $ "Websocket listener task faulted: { task . Exception } ") ;
151
- throw task . Exception ;
152
168
} , TaskContinuationOptions . OnlyOnFaulted ) ;
153
169
}
154
170
0 commit comments