66using System . Text ;
77using System . Threading ;
88using System . Threading . Tasks ;
9- using Serilog ;
9+ using Websocket . Client . Logging ;
1010
1111namespace Websocket . Client
1212{
@@ -15,6 +15,8 @@ namespace Websocket.Client
1515 /// </summary>
1616 public class WebsocketClient : IWebsocketClient
1717 {
18+ private static readonly ILog Logger = LogProvider . GetCurrentClassLogger ( ) ;
19+
1820 private readonly Uri _url ;
1921 private Timer _lastChanceTimer ;
2022 private readonly Func < ClientWebSocket > _clientFactory ;
@@ -23,8 +25,8 @@ public class WebsocketClient : IWebsocketClient
2325
2426 private bool _disposing = false ;
2527 private ClientWebSocket _client ;
26- private CancellationTokenSource _cancelation ;
27- private CancellationTokenSource _cancelationTotal ;
28+ private CancellationTokenSource _cancellation ;
29+ private CancellationTokenSource _cancellationTotal ;
2830
2931 private readonly Subject < string > _messageReceivedSubject = new Subject < string > ( ) ;
3032 private readonly Subject < ReconnectionType > _reconnectionSubject = new Subject < ReconnectionType > ( ) ;
@@ -50,12 +52,12 @@ public WebsocketClient(Uri url, Func<ClientWebSocket> clientFactory = null)
5052 public IObservable < string > MessageReceived => _messageReceivedSubject . AsObservable ( ) ;
5153
5254 /// <summary>
53- /// Stream for reconnection event (trigerred after the new connection)
55+ /// Stream for reconnection event (triggered after the new connection)
5456 /// </summary>
5557 public IObservable < ReconnectionType > ReconnectionHappened => _reconnectionSubject . AsObservable ( ) ;
5658
5759 /// <summary>
58- /// Stream for disconnection event (trigerred after the connection was lost)
60+ /// Stream for disconnection event (triggered after the connection was lost)
5961 /// </summary>
6062 public IObservable < DisconnectionType > DisconnectionHappened => _disconnectedSubject . AsObservable ( ) ;
6163
@@ -71,6 +73,12 @@ public WebsocketClient(Uri url, Func<ClientWebSocket> clientFactory = null)
7173 /// </summary>
7274 public int ErrorReconnectTimeoutMs { get ; set ; } = 60 * 1000 ;
7375
76+ /// <summary>
77+ /// Get or set the name of the current websocket client instance.
78+ /// For logging purpose (in case you use more parallel websocket clients and want to distinguish between them)
79+ /// </summary>
80+ public string Name { get ; set ; }
81+
7482 /// <summary>
7583 /// Returns true if Start() method was called at least once. False if not started or disposed
7684 /// </summary>
@@ -87,21 +95,21 @@ public WebsocketClient(Uri url, Func<ClientWebSocket> clientFactory = null)
8795 public void Dispose ( )
8896 {
8997 _disposing = true ;
90- Log . Debug ( L ( "Disposing.." ) ) ;
98+ Logger . Debug ( L ( "Disposing.." ) ) ;
9199 try
92100 {
93101 _lastChanceTimer ? . Dispose ( ) ;
94- _cancelation ? . Cancel ( ) ;
95- _cancelationTotal ? . Cancel ( ) ;
102+ _cancellation ? . Cancel ( ) ;
103+ _cancellationTotal ? . Cancel ( ) ;
96104 _client ? . Abort ( ) ;
97105 _client ? . Dispose ( ) ;
98- _cancelation ? . Dispose ( ) ;
99- _cancelationTotal ? . Dispose ( ) ;
106+ _cancellation ? . Dispose ( ) ;
107+ _cancellationTotal ? . Dispose ( ) ;
100108 _messagesToSendQueue ? . Dispose ( ) ;
101109 }
102110 catch ( Exception e )
103111 {
104- Log . Error ( e , L ( $ "Failed to dispose client, error: { e . Message } ") ) ;
112+ Logger . Error ( e , L ( $ "Failed to dispose client, error: { e . Message } ") ) ;
105113 }
106114
107115 IsStarted = false ;
@@ -115,16 +123,16 @@ public async Task Start()
115123 {
116124 if ( IsStarted )
117125 {
118- Log . Debug ( L ( "Client already started, ignoring.." ) ) ;
126+ Logger . Debug ( L ( "Client already started, ignoring.." ) ) ;
119127 return ;
120128 }
121129 IsStarted = true ;
122130
123- Log . Debug ( L ( "Starting.." ) ) ;
124- _cancelation = new CancellationTokenSource ( ) ;
125- _cancelationTotal = new CancellationTokenSource ( ) ;
131+ Logger . Debug ( L ( "Starting.." ) ) ;
132+ _cancellation = new CancellationTokenSource ( ) ;
133+ _cancellationTotal = new CancellationTokenSource ( ) ;
126134
127- await StartClient ( _url , _cancelation . Token , ReconnectionType . Initial ) . ConfigureAwait ( false ) ;
135+ await StartClient ( _url , _cancellation . Token , ReconnectionType . Initial ) . ConfigureAwait ( false ) ;
128136
129137 StartBackgroundThreadForSending ( ) ;
130138 }
@@ -164,7 +172,7 @@ public async Task Reconnect()
164172 {
165173 if ( ! IsStarted )
166174 {
167- Log . Debug ( L ( "Client not started, ignoring reconnection.." ) ) ;
175+ Logger . Debug ( L ( "Client not started, ignoring reconnection.." ) ) ;
168176 return ;
169177 }
170178 await Reconnect ( ReconnectionType . ByUser ) . ConfigureAwait ( false ) ;
@@ -174,15 +182,15 @@ private async Task SendFromQueue()
174182 {
175183 try
176184 {
177- foreach ( var message in _messagesToSendQueue . GetConsumingEnumerable ( _cancelationTotal . Token ) )
185+ foreach ( var message in _messagesToSendQueue . GetConsumingEnumerable ( _cancellationTotal . Token ) )
178186 {
179187 try
180188 {
181189 await SendInternal ( message ) . ConfigureAwait ( false ) ;
182190 }
183191 catch ( Exception e )
184192 {
185- Log . Error ( L ( $ "Failed to send message: '{ message } '. Error: { e . Message } ") ) ;
193+ Logger . Error ( L ( $ "Failed to send message: '{ message } '. Error: { e . Message } ") ) ;
186194 }
187195 }
188196 }
@@ -192,7 +200,7 @@ private async Task SendFromQueue()
192200 }
193201 catch ( Exception e )
194202 {
195- if ( _cancelationTotal . IsCancellationRequested || _disposing )
203+ if ( _cancellationTotal . IsCancellationRequested || _disposing )
196204 {
197205 // disposing/canceling, do nothing and exit
198206 return ;
@@ -206,22 +214,22 @@ private async Task SendFromQueue()
206214 private void StartBackgroundThreadForSending ( )
207215 {
208216#pragma warning disable 4014
209- Task . Factory . StartNew ( _ => SendFromQueue ( ) , TaskCreationOptions . LongRunning , _cancelationTotal . Token ) ;
217+ Task . Factory . StartNew ( _ => SendFromQueue ( ) , TaskCreationOptions . LongRunning , _cancellationTotal . Token ) ;
210218#pragma warning restore 4014
211219 }
212220
213221 private async Task SendInternal ( string message )
214222 {
215- Log . Verbose ( L ( $ "Sending: { message } ") ) ;
223+ Logger . Trace ( L ( $ "Sending: { message } ") ) ;
216224 var buffer = Encoding . UTF8 . GetBytes ( message ) ;
217225 var messageSegment = new ArraySegment < byte > ( buffer ) ;
218226 var client = await GetClient ( ) . ConfigureAwait ( false ) ;
219- await client . SendAsync ( messageSegment , WebSocketMessageType . Text , true , _cancelation . Token ) . ConfigureAwait ( false ) ;
227+ await client . SendAsync ( messageSegment , WebSocketMessageType . Text , true , _cancellation . Token ) . ConfigureAwait ( false ) ;
220228 }
221229
222230 private async Task StartClient ( Uri uri , CancellationToken token , ReconnectionType type )
223231 {
224- DeactiveLastChance ( ) ;
232+ DeactivateLastChance ( ) ;
225233 _client = _clientFactory ( ) ;
226234
227235 try
@@ -237,7 +245,7 @@ private async Task StartClient(Uri uri, CancellationToken token, ReconnectionTyp
237245 catch ( Exception e )
238246 {
239247 _disconnectedSubject . OnNext ( DisconnectionType . Error ) ;
240- Log . Error ( e , L ( "Exception while connecting. " +
248+ Logger . Error ( e , L ( "Exception while connecting. " +
241249 $ "Waiting { ErrorReconnectTimeoutMs / 1000 } sec before next reconnection try.") ) ;
242250 await Task . Delay ( ErrorReconnectTimeoutMs , token ) . ConfigureAwait ( false ) ;
243251 await Reconnect ( ReconnectionType . Error ) . ConfigureAwait ( false ) ;
@@ -261,12 +269,12 @@ private async Task Reconnect(ReconnectionType type)
261269 if ( type != ReconnectionType . Error )
262270 _disconnectedSubject . OnNext ( TranslateTypeToDisconnection ( type ) ) ;
263271
264- Log . Debug ( L ( "Reconnecting..." ) ) ;
265- _cancelation . Cancel ( ) ;
272+ Logger . Debug ( L ( "Reconnecting..." ) ) ;
273+ _cancellation . Cancel ( ) ;
266274 await Task . Delay ( 1000 ) . ConfigureAwait ( false ) ;
267275
268- _cancelation = new CancellationTokenSource ( ) ;
269- await StartClient ( _url , _cancelation . Token , type ) . ConfigureAwait ( false ) ;
276+ _cancellation = new CancellationTokenSource ( ) ;
277+ await StartClient ( _url , _cancellation . Token , type ) . ConfigureAwait ( false ) ;
270278 }
271279
272280 private async Task Listen ( ClientWebSocket client , CancellationToken token )
@@ -290,7 +298,7 @@ private async Task Listen(ClientWebSocket client, CancellationToken token)
290298 } while ( ! result . EndOfMessage ) ;
291299
292300 var received = resultMessage . ToString ( ) ;
293- Log . Verbose ( L ( $ "Received: { received } ") ) ;
301+ Logger . Trace ( L ( $ "Received: { received } ") ) ;
294302 _lastReceivedMsg = DateTime . UtcNow ;
295303 _messageReceivedSubject . OnNext ( received ) ;
296304
@@ -302,7 +310,7 @@ private async Task Listen(ClientWebSocket client, CancellationToken token)
302310 }
303311 catch ( Exception e )
304312 {
305- Log . Error ( e , L ( "Error while listening to websocket stream" ) ) ;
313+ Logger . Error ( e , L ( "Error while listening to websocket stream" ) ) ;
306314 }
307315 }
308316
@@ -312,7 +320,7 @@ private void ActivateLastChance()
312320 _lastChanceTimer = new Timer ( LastChance , null , timerMs , timerMs ) ;
313321 }
314322
315- private void DeactiveLastChance ( )
323+ private void DeactivateLastChance ( )
316324 {
317325 _lastChanceTimer ? . Dispose ( ) ;
318326 _lastChanceTimer = null ;
@@ -324,9 +332,9 @@ private void LastChance(object state)
324332 var diffMs = Math . Abs ( DateTime . UtcNow . Subtract ( _lastReceivedMsg ) . TotalMilliseconds ) ;
325333 if ( diffMs > timeoutMs )
326334 {
327- Log . Debug ( L ( $ "Last message received more than { timeoutMs : F} ms ago. Hard restart..") ) ;
335+ Logger . Debug ( L ( $ "Last message received more than { timeoutMs : F} ms ago. Hard restart..") ) ;
328336
329- DeactiveLastChance ( ) ;
337+ DeactivateLastChance ( ) ;
330338 _client ? . Abort ( ) ;
331339 _client ? . Dispose ( ) ;
332340#pragma warning disable 4014
@@ -337,12 +345,13 @@ private void LastChance(object state)
337345
338346 private string L ( string msg )
339347 {
340- return $ "[WEBSOCKET CLIENT] { msg } ";
348+ var name = Name ?? "CLIENT" ;
349+ return $ "[WEBSOCKET { name } ] { msg } ";
341350 }
342351
343352 private DisconnectionType TranslateTypeToDisconnection ( ReconnectionType type )
344353 {
345- // beaware enum indexes must correspond to each other
354+ // beware enum indexes must correspond to each other
346355 return ( DisconnectionType ) type ;
347356 }
348357 }
0 commit comments