public async Task ConnectAsync() { if (Socket == null) { Socket = new ClientWebSocket(); CancellationSource = new CancellationTokenSource(); } Task connectTask; try { connectTask = Socket.ConnectAsync(TargetUri, CancellationSource.Token); connectTask.Wait(); } catch (Exception e) { Console.WriteLine(String.Format("Connection task threw exception on connect = {0}", e.ToString())); await CloseAsync("Exception on connect."); return; } if (!connectTask.IsCompletedSuccessfully) { Console.WriteLine("Connection task completed unsuccessfully."); await CloseAsync("Connection task unsuccessful."); return; } OnConnected?.Invoke(this); ReceiveLoop.Start(); }
public async Task CloseAsync(string message, WebSocketCloseStatus status = WebSocketCloseStatus.NormalClosure) { if (Socket == null) { return; } Task receiveTask = ReceiveLoop.StopAsync(); try { using var closeToken = new CancellationTokenSource(TimeSpan.FromSeconds(3)); await Socket?.CloseAsync(status, message, closeToken.Token); } catch (Exception e) { Console.WriteLine(String.Format("Exception while closing : {0}", e.ToString())); } finally { CancellationSource?.Cancel(); Socket?.Dispose(); Socket = null; CancellationSource?.Dispose(); CancellationSource = null; } }
public static ReceiveLoop EnableSuspendResume(this ReceiveLoop loop, Inbox inbox) { return(loop.Receive <Suspend>(pause => { // we are going to only receive a continue until we get it inbox.Receive <Resume>(x => { // repeat the loop now loop.Continue(); }); })); }
public static ReceiveLoop Receive <T>(this ReceiveLoop loop, Consumer <T> consumer) { return(loop.Receive <T>(x => consumer)); }