private async Task ConnectInternalAsync(string host) { await DisconnectInternalAsync().ConfigureAwait(false); _disconnectCancelTokenSource?.Dispose(); _cancelTokenSource?.Dispose(); _client?.Dispose(); _disconnectCancelTokenSource = new CancellationTokenSource(); _cancelTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_parentToken, _disconnectCancelTokenSource.Token); _cancelToken = _cancelTokenSource.Token; _client = new WS4NetSocket(host, "", customHeaderItems: _headers.ToList()) { EnableAutoSendPing = false, NoDelay = true, Proxy = null }; _client.MessageReceived += OnTextMessage; _client.DataReceived += OnBinaryMessage; _client.Opened += OnConnected; _client.Closed += OnClosed; _client.Open(); _waitUntilConnect.Wait(_cancelToken); }
private Task DisconnectInternalAsync(int closeCode = 1000, bool isDisposing = false) { _disconnectCancelTokenSource.Cancel(); if (_client == null) { return(Task.Delay(0)); } if (_client.State == WebSocketState.Open) { try { _client.Close(closeCode, ""); } catch { } } _client.MessageReceived -= OnTextMessage; _client.DataReceived -= OnBinaryMessage; _client.Opened -= OnConnected; _client.Closed -= OnClosed; try { _client.Dispose(); } catch { } _client = null; _waitUntilConnect.Reset(); return(Task.Delay(0)); }
public void Dispose() { if (_webSocket != null) { _webSocket.DataReceived -= OnDataReceived; _webSocket.Dispose(); } }
// // Excel calls this when it wants to shut down RTD server. // void IRtdServer.ServerTerminate() { if (_timer != null) { _timer.Stop(); _timer = null; } if (_socket != null) { _socket.Dispose(); _socket = null; } }
protected virtual void Dispose(bool disposing) { if (m_disposed) { return; } if (disposing) { if (m_WebSocket != null) { m_WebSocket.Dispose(); } } m_disposed = true; }
/// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing) { Logger.Verbose($"[{SessionKey}] Disposing EtpClient for {GetType().Name}"); UnsubscribeFromSocketEvents(); CloseWebSocket("Shutting down"); _socket?.Dispose(); Logger.Verbose($"[{SessionKey}] Disposed EtpClient for {GetType().Name}"); } base.Dispose(disposing); _socket = null; }
public async Task StreamAsync(Uri uri, CancellationToken token) { Throw.IfNull(uri, nameof(uri)); if (!token.CanBeCanceled) { throw new ArgumentException("Token must be capable of being in the canceled state.", nameof(token)); } token.ThrowIfCancellationRequested(); IsStreaming = true; var webSocket = new WebSocket4Net.WebSocket(uri.ToString(), "basic", WebSocketVersion.Rfc6455); webSocket.Security.AllowUnstrustedCertificate = true; webSocket.Security.AllowNameMismatchCertificate = true; webSocket.EnableAutoSendPing = true; webSocket.DataReceived += WebSocket_DataReceived; //var webSocket = new ClientWebSocket(); //webSocket.Options.KeepAliveInterval = TimeSpan.FromSeconds(30); try { try { webSocket.Open(); if (webSocket.State == WebSocketState.Open) { RaiseOpenEvent(); } } catch (OperationCanceledException) { } catch (Exception e) { if (!token.IsCancellationRequested) { _logger?.LogError(e, $"{nameof(WebSocketClient)}.{nameof(StreamAsync)}: WebSocket connect exception."); throw; } } while (!token.IsCancellationRequested) { // do nothing } /* * * var bytes = new byte[ReceiveBufferSize]; * var buffer = new ArraySegment<byte>(bytes); * * while (!token.IsCancellationRequested) * { * var stringBuilder = new StringBuilder(); * stringBuilder.Clear(); * * try * { * WebSocketReceiveResult result; * do * { * if (webSocket.State != WebSocketState.Open) * { * throw new Exception($"{nameof(WebSocketClient)}.{nameof(StreamAsync)}: WebSocket is not open (state: {webSocket.State})."); * } * * result = await webSocket * .ReceiveAsync(buffer, token) * .ConfigureAwait(false); * * switch (result.MessageType) * { * case WebSocketMessageType.Close: * throw new Exception(result.CloseStatus.HasValue * ? $"{nameof(WebSocketClient)}.{nameof(StreamAsync)}: WebSocket closed ({result.CloseStatus.Value}): \"{result.CloseStatusDescription ?? "[no reason provided]"}\"" * : $"{nameof(WebSocketClient)}.{nameof(StreamAsync)}: WebSocket closed: \"{result.CloseStatusDescription ?? "[no reason provided]"}\""); * * case WebSocketMessageType.Text when result.Count > 0: * stringBuilder.Append(Encoding.UTF8.GetString(bytes, 0, result.Count)); * break; * * case WebSocketMessageType.Binary: * _logger?.LogWarning($"{nameof(WebSocketClient)}.{nameof(StreamAsync)}: Received unsupported binary message type."); * break; * * default: * throw new ArgumentOutOfRangeException(nameof(result.MessageType), $"{nameof(WebSocketClient)}.{nameof(StreamAsync)}: Unknown result message type ({result.MessageType})."); * } * } * while (!result.EndOfMessage); * } * catch (OperationCanceledException) { } * catch (Exception e) * { * if (!token.IsCancellationRequested) * { * _logger?.LogError(e, $"{nameof(WebSocketClient)}.{nameof(StreamAsync)}: WebSocket receive exception."); * throw; * } * } * * if (token.IsCancellationRequested) * continue; * * var json = stringBuilder.ToString(); * if (!string.IsNullOrWhiteSpace(json)) * { * RaiseMessageEvent(new WebSocketClientEventArgs(json)); * } * else * { * _logger?.LogWarning($"{nameof(WebSocketClient)}.{nameof(StreamAsync)}: Received empty JSON message."); * } * } */ } finally { IsStreaming = false; // NOTE: WebSocketState.CloseSent should not be encountered since CloseOutputAsync is not used. if (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.Closing) { webSocket.Close(); //await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).ConfigureAwait(false); } if (webSocket != null) { webSocket.Dispose(); } RaiseCloseEvent(); } }
public void Dispose() { webSocketFeed.Dispose(); }
public static void OnClose() { isOpened = false; websocket.Dispose(); }
public void Disconnect() { socket.Dispose(); }