public void ConstructorTests_WebSocketError_Success(WebSocketError error) { var wse = new WebSocketException(error); Assert.Equal(error, wse.WebSocketErrorCode); Assert.NotEqual("", wse.Message); Assert.Null(wse.InnerException); }
public void ConstructorTests_WebSocketError_Exception_Success(WebSocketError error) { var inner = new Exception(); var wse = new WebSocketException(error, inner); Assert.Equal(error, wse.WebSocketErrorCode); Assert.NotEqual("", wse.Message); Assert.Same(inner, wse.InnerException); }
public void ConstructorTests_WebSocketError_Message_Success(WebSocketError error) { const string Message = "Message"; var wse = new WebSocketException(error, Message); Assert.Equal(error, wse.WebSocketErrorCode); Assert.Equal(Message, wse.Message); Assert.Null(wse.InnerException); }
public void ConstructorTests_NativeError_Success(int nativeError, WebSocketError webSocketError, int expectedHResult) { var wse = new WebSocketException(nativeError); Assert.Equal(expectedHResult, wse.HResult); Assert.Equal(webSocketError, wse.WebSocketErrorCode); Assert.NotEqual("", wse.Message); Assert.Null(wse.InnerException); }
public void ConstructorTests_NativeError_Success(int nativeError, WebSocketError webSocketError) { var wse = new WebSocketException(nativeError); Assert.Equal(wse.HResult, nativeError); Assert.Equal(wse.WebSocketErrorCode, webSocketError); Assert.NotEqual(wse.Message, ""); Assert.Null(wse.InnerException); }
public void ConstructorTests_NativeError_Message_Success(int nativeError, WebSocketError webSocketError) { const string Message = "Message"; var wse = new WebSocketException(nativeError, Message); Assert.Equal(wse.HResult, nativeError); Assert.Equal(wse.WebSocketErrorCode, webSocketError); Assert.Equal(wse.Message, Message); Assert.Null(wse.InnerException); }
public void ConstructorTests_WebSocketError_Message_Exception_Success(WebSocketError error) { const string Message = "Message"; var inner = new Exception(); var wse = new WebSocketException(error, Message, inner); Assert.Equal(wse.WebSocketErrorCode, error); Assert.Equal(wse.Message, Message); Assert.Equal(wse.InnerException, inner); }
public WebSocketException(int nativeError, string message) : base(nativeError, message) { m_WebSocketErrorCode = !WebSocketProtocolComponent.Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success; this.SetErrorCodeOnError(nativeError); }
public WebSocketException(int nativeError, string message) : base(nativeError, message) { m_WebSocketErrorCode = !WebSocketProtocolComponent.Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success; this.SetErrorCodeOnError(nativeError); }
private static string GetErrorMessage(WebSocketError error) { // provide a canned message for the error type switch (error) { case WebSocketError.InvalidMessageType: return SR.GetString(SR.net_WebSockets_InvalidMessageType_Generic, typeof(WebSocket).Name + WebSocketBase.Methods.CloseAsync, typeof(WebSocket).Name + WebSocketBase.Methods.CloseOutputAsync); case WebSocketError.Faulted: return SR.GetString(SR.net_Websockets_WebSocketBaseFaulted); case WebSocketError.NotAWebSocket: return SR.GetString(SR.net_WebSockets_NotAWebSocket_Generic); case WebSocketError.UnsupportedVersion: return SR.GetString(SR.net_WebSockets_UnsupportedWebSocketVersion_Generic); case WebSocketError.UnsupportedProtocol: return SR.GetString(SR.net_WebSockets_UnsupportedProtocol_Generic); case WebSocketError.HeaderError: return SR.GetString(SR.net_WebSockets_HeaderError_Generic); case WebSocketError.ConnectionClosedPrematurely: return SR.GetString(SR.net_WebSockets_ConnectionClosedPrematurely_Generic); case WebSocketError.InvalidState: return SR.GetString(SR.net_WebSockets_InvalidState_Generic); default: return SR.GetString(SR.net_WebSockets_Generic); } }
public WebSocketException (WebSocketError error, string message) : this (error, -1, message, null) { }
public WebSocketException(int nativeError, Exception innerException) : base(SR.net_WebSockets_Generic, innerException) { _webSocketErrorCode = !Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success; SetErrorCodeOnError(nativeError); }
void socketIO_Error(object sender, ErrorEventArgs e) { WebErrorStatus status = WebSocketError.GetStatus(e.Exception.HResult); Debug.WriteLine("-->SOCKET_IO_ERROR::" + status); }
public WebSocketException (WebSocketError error, int nativeError, string message) : base (nativeError, message) { WebSocketErrorCode = error; }
private async Task CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus closeStatus, WebSocketError error, CancellationToken cancellationToken, Exception innerException = null) { if (!_sentCloseFrame) { await CloseOutputAsync(closeStatus, string.Empty, cancellationToken).ConfigureAwait(false); } _receiveBufferCount = 0; throw new WebSocketException(error, innerException); }
private void OnMessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { // GetDataReader() throws an exception when either: // (1) The underlying TCP connection is closed prematurely (e.g., FIN/RST received without sending/receiving a WebSocket Close frame). // (2) The server sends invalid data (e.g., corrupt HTTP headers or a message exceeding the MaxMessageSize). // // In both cases, the appropriate thing to do is to close the socket, as we have reached an unexpected state in // the WebSocket protocol. try { using (DataReader reader = args.GetDataReader()) { uint dataAvailable; while ((dataAvailable = reader.UnconsumedBufferLength) > 0) { ArraySegment <byte> buffer; try { buffer = _receiveAsyncBufferTcs.Task.GetAwaiter().GetResult(); } catch (OperationCanceledException) // Caused by Abort call on WebSocket { return; } _receiveAsyncBufferTcs = new TaskCompletionSource <ArraySegment <byte> >(); WebSocketMessageType messageType; if (args.MessageType == SocketMessageType.Binary) { messageType = WebSocketMessageType.Binary; } else { messageType = WebSocketMessageType.Text; } bool endOfMessage = false; uint readCount = Math.Min(dataAvailable, (uint)buffer.Count); var dataBuffer = reader.ReadBuffer(readCount); // Safe to cast readCount to int as the maximum value that readCount can be is buffer.Count. dataBuffer.CopyTo(0, buffer.Array, buffer.Offset, (int)readCount); if (dataAvailable == readCount) { endOfMessage = true; } WebSocketReceiveResult recvResult = new WebSocketReceiveResult((int)readCount, messageType, endOfMessage); _webSocketReceiveResultTcs.TrySetResult(recvResult); } } } catch (Exception exc) { // WinRT WebSockets always throw exceptions of type System.Exception. However, we can determine whether // or not we're dealing with a known error by using WinRT's WebSocketError.GetStatus method. WebErrorStatus status = RTWebSocketError.GetStatus(exc.HResult); WebSocketError actualError = WebSocketError.Faulted; switch (status) { case WebErrorStatus.ConnectionAborted: case WebErrorStatus.ConnectionReset: case WebErrorStatus.Disconnected: actualError = WebSocketError.ConnectionClosedPrematurely; break; } // Propagate a custom exception to any pending SendAsync/ReceiveAsync operations and close the socket. WebSocketException customException = new WebSocketException(actualError, exc); AbortInternal(customException); } }
private static async Task<List<Download>> FromCurse(Addon addon) { var downloads = new List<Download>(); try { for (int i = 1; i < 5; i++) { var uri = new Uri("https://www.curseforge.com/wow/addons/" + addon.ProjectUrl + "/files?page=" + i); var htmlPage = await Http.WebHttpClient.GetStringAsync(uri); var fresh = Parse.FromPageToDownloads(addon, htmlPage).Where(d => { var dGameVersion = d.GameVersion.First().ToString(); if (addon.GameType == GAME_TYPE.RETAIL) { return dGameVersion == "8"; } if (addon.GameType == GAME_TYPE.CLASSIC) { return dGameVersion == "1"; } return false; }).ToList(); var dontExistAllready = fresh.Except(addon.Downloads).ToList(); if (dontExistAllready.Count == 0) { // Debug.WriteLine("Should be in addon allready " + addon.FolderName); return downloads; } var newPage = dontExistAllready.Except(downloads).ToList(); if (newPage.Count == 0) { // Debug.WriteLine("Should be same page return " + addon.FolderName); return downloads; } downloads.AddRange(newPage); if (downloads.Any(d => d.ReleaseType.Equals("Release", StringComparison.OrdinalIgnoreCase)) && downloads.Any(d => d.ReleaseType.Equals("Beta", StringComparison.OrdinalIgnoreCase)) && downloads.Any(d => d.ReleaseType.Equals("Alpha", StringComparison.OrdinalIgnoreCase)) ) { return downloads; } } return downloads; } catch (Exception ex) { var error = WebSocketError.GetStatus(ex.HResult); if (error == Windows.Web.WebErrorStatus.Unknown) { Debug.WriteLine("[ERROR] DownloadVersionsFor " + addon.ProjectUrl + " " + error + " " + ex.Message); } else { Debug.WriteLine("[ERROR] DownloadVersionsFor " + addon.ProjectUrl + " " + ex.Message); } } return new List<Download>(); }
public async Task ConnectAsync_NotWebSocketServer_ThrowsWebSocketExceptionWithMessage(Uri server, string exceptionMessage, WebSocketError errorCode) { using (var cws = new ClientWebSocket()) { var cts = new CancellationTokenSource(TimeOutMilliseconds); WebSocketException ex = await Assert.ThrowsAsync <WebSocketException>(() => cws.ConnectAsync(server, cts.Token)); if (PlatformDetection.IsNetCore && !PlatformDetection.IsUap) // bug fix in netcoreapp: https://github.com/dotnet/corefx/pull/35960 { Assert.Equal(errorCode, ex.WebSocketErrorCode); } Assert.Equal(WebSocketState.Closed, cws.State); // .NET Framework and UAP implmentations have different exception message from .NET Core. if (!PlatformDetection.IsUap) { Assert.Equal(exceptionMessage, ex.Message); } } }
public async void Connect(string url) { if (pending != null) { pending.Dispose(); } Uri uri; var connectionId = Strings.RandomString(8); var serverId = Strings.RandomNumber(1, 1000); try { uri = new Uri(url); } catch (Exception) { throw new OrtcException(OrtcExceptionReason.InvalidArguments, String.Format("Invalid URL: {0}", url)); } try { var prefix = "https".Equals(uri.Scheme) ? "wss" : "ws"; var connectionUrl = new Uri(String.Format("{0}://{1}:{2}/broadcast/{3}/{4}/websocket", prefix, uri.DnsSafeHost, uri.Port, serverId, connectionId)); pending = new MessageWebSocket(); pending.Control.MessageType = SocketMessageType.Utf8; pending.Closed += Closed; pending.MessageReceived += MessageReceived; try { await pending.ConnectAsync(connectionUrl); } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); switch (status) { case WebErrorStatus.CannotConnect: throw new Exception("Can't connect" + ex.Message); case WebErrorStatus.NotFound: throw new Exception("Not found" + ex.Message); case WebErrorStatus.RequestTimeout: throw new Exception("Request timeout" + ex.Message); default: throw new Exception("unknown" + ex.Message); } } streamWebSocket = pending; messageWriter = new DataWriter(pending.OutputStream); var ev = _onOpened; if (ev != null) { ev(); } } catch { throw new OrtcException(OrtcExceptionReason.InvalidArguments, String.Format("Invalid URL: {0}", url)); } }
public async Task ConnectAsync_NotWebSocketServer_ThrowsWebSocketExceptionWithMessage(Uri server, string exceptionMessage, WebSocketError errorCode) { using (var cws = new ClientWebSocket()) { var cts = new CancellationTokenSource(TimeOutMilliseconds); WebSocketException ex = await Assert.ThrowsAsync <WebSocketException>(() => cws.ConnectAsync(server, cts.Token)); if (PlatformDetection.IsNetCore && !PlatformDetection.IsInAppContainer) // bug fix in netcoreapp: https://github.com/dotnet/corefx/pull/35960 { Assert.Equal(errorCode, ex.WebSocketErrorCode); } Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(exceptionMessage, ex.Message); // Other operations throw after failed connect await Assert.ThrowsAsync <ObjectDisposedException>(() => cws.ReceiveAsync(new byte[1], default)); await Assert.ThrowsAsync <ObjectDisposedException>(() => cws.SendAsync(new byte[1], WebSocketMessageType.Binary, true, default)); await Assert.ThrowsAsync <ObjectDisposedException>(() => cws.CloseAsync(WebSocketCloseStatus.NormalClosure, null, default)); await Assert.ThrowsAsync <ObjectDisposedException>(() => cws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, default)); } }
/// <summary>Send a close message to the server and throw an exception, in response to getting bad data from the server.</summary> /// <param name="closeStatus">The close status code to use.</param> /// <param name="error">The error reason.</param> /// <param name="cancellationToken">The CancellationToken used to cancel the websocket.</param> /// <param name="innerException">An optional inner exception to include in the thrown exception.</param> private async Task CloseWithReceiveErrorAndThrowAsync( WebSocketCloseStatus closeStatus, WebSocketError error, CancellationToken cancellationToken, Exception innerException = null) { // Close the connection if it hasn't already been closed if (!_sentCloseFrame) { await CloseOutputAsync(closeStatus, string.Empty, cancellationToken).ConfigureAwait(false); } // Dump our receive buffer; we're in a bad state to do any further processing _receiveBufferCount = 0; // Let the caller know we've failed throw new WebSocketException(error, innerException); }
public void ConstructorTests_WebSocketError_NativeError_Message_Success(int nativeError, WebSocketError error) { const string Message = "Message"; var wse = new WebSocketException(error, nativeError, Message); Assert.Equal(wse.HResult, nativeError); Assert.Equal(wse.WebSocketErrorCode, error); Assert.Equal(wse.Message, Message); Assert.Null(wse.InnerException); }
public WebSocketException (WebSocketError error) : this (error, -1, DefaultMessage, null) { }
public void ConstructorTests_WebSocketError_NativeError_Exception_Success(int nativeError, WebSocketError error) { var inner = new Exception(); var wse = new WebSocketException(error, nativeError, inner); Assert.Equal(wse.HResult, nativeError); Assert.Equal(wse.WebSocketErrorCode, error); Assert.NotEqual(wse.Message, ""); Assert.Equal(wse.InnerException, inner); }
public WebSocketException (WebSocketError error, int nativeError, string message) : this (error, nativeError, message, null) { }
private static string GetErrorMessage(WebSocketError error) => // Provide a canned message for the error type. error switch {
public WebSocketException(WebSocketError error, Exception innerException) : this(error, GetErrorMessage(error), innerException) { }
public WebSocketException(WebSocketError error, int nativeError, string?message) : base(message) { _webSocketErrorCode = error; SetErrorCodeOnError(nativeError); }
public WebSocketException(WebSocketError error, int nativeError) : this(error, nativeError, GetErrorMessage(error)) { }
public WebSocketException(WebSocketError error, int nativeError, Exception?innerException) : this(error, nativeError, GetErrorMessage(error), innerException) { }
public void ConstructorTests_WebSocketError_NativeError_Exception_Success(int nativeError, WebSocketError error) { var inner = new Exception(); var wse = new WebSocketException(error, nativeError, inner); Assert.Equal(wse.HResult, nativeError); Assert.Equal(wse.WebSocketErrorCode, error); Assert.NotEqual(wse.Message, ""); Assert.Equal(wse.InnerException, inner); }
private void OnError(object sender, WebSocketError e) { Log.Error($"BitfinexSubscriptionManager.OnError(): Message: {e.Message} Exception: {e.Exception}"); }
public void ConstructorTests_WebSocketError_NativeError_Message_Exception_Success(int nativeError, WebSocketError error, int expectedHResult) { const string Message = "Message"; var inner = new Exception(); var wse = new WebSocketException(error, nativeError, Message, inner); Assert.Equal(expectedHResult, wse.HResult); Assert.Equal(error, wse.WebSocketErrorCode); Assert.Equal(Message, wse.Message); Assert.Same(inner, wse.InnerException); }
public WebSocketException(WebSocketError error, int nativeError, string message) : base(message) { m_WebSocketErrorCode = error; this.SetErrorCodeOnError(nativeError); }
private static string GetErrorMessage(WebSocketError error) { // Provide a canned message for the error type. switch (error) { case WebSocketError.InvalidMessageType: return SR.Format(SR.net_WebSockets_InvalidMessageType_Generic, $"{nameof(WebSocket)}.{nameof(WebSocket.CloseAsync)}", $"{nameof(WebSocket)}.{nameof(WebSocket.CloseOutputAsync)}"); case WebSocketError.Faulted: return SR.net_Websockets_WebSocketBaseFaulted; case WebSocketError.NotAWebSocket: return SR.net_WebSockets_NotAWebSocket_Generic; case WebSocketError.UnsupportedVersion: return SR.net_WebSockets_UnsupportedWebSocketVersion_Generic; case WebSocketError.UnsupportedProtocol: return SR.net_WebSockets_UnsupportedProtocol_Generic; case WebSocketError.HeaderError: return SR.net_WebSockets_HeaderError_Generic; case WebSocketError.ConnectionClosedPrematurely: return SR.net_WebSockets_ConnectionClosedPrematurely_Generic; case WebSocketError.InvalidState: return SR.net_WebSockets_InvalidState_Generic; default: return SR.net_WebSockets_Generic; } }
/// <summary> /// Connect to MX server /// </summary> /// <param name="host">The MX server host address</param> /// <param name="port">The MX server CSTA port number 7777 or 7778 for TLS</param> /// <param name="useTls">Use TLS for connection to server</param> /// <returns>False if the connection is not set</returns> public async Task <bool> Connect(string host, string port, ConnectType type) { if (CoreApplication.Properties.ContainsKey("clientSocket")) { return(false); } if (type == ConnectType.WebSocketSecure) { return(false); } HostName hostName; try { hostName = new HostName(host); } catch (ArgumentException) { return(false); } StreamSocket socket = null; // = new StreamSocket(); StreamWebSocket streamWebSocket = null; switch (type) { case ConnectType.Plain: try { socket = new StreamSocket(); socket.Control.KeepAlive = false; // Connect to the server (by default, the listener we created in the previous step). await socket.ConnectAsync(hostName, port); // Mark the socket as connected. Set the value to null, as we care only about the fact that the // property is set. } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } return(false); } break; case ConnectType.Secure: socket = new StreamSocket(); socket.Control.KeepAlive = true; socket.Control.NoDelay = false; // socket.Control.ClientCertificate = null; bool shouldRetry = await TryConnectSocketWithRetryAsync(socket, hostName, port); if (shouldRetry) { // Retry if the first attempt failed because of SSL errors. if (await TryConnectSocketWithRetryAsync(socket, hostName, port)) { return(false); } } break; case ConnectType.WebSocket: try { streamWebSocket = new StreamWebSocket(); Uri server = new Uri(string.Format("ws://{0}:{1}", host, port)); // Dispatch close event on UI thread. This allows us to avoid synchronizing access to streamWebSocket. streamWebSocket.Closed += async(senderSocket, args) => { var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher; await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Closed(senderSocket, args)); }; await streamWebSocket.ConnectAsync(server); } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); switch (status) { case WebErrorStatus.CannotConnect: case WebErrorStatus.NotFound: case WebErrorStatus.RequestTimeout: break; case WebErrorStatus.Unknown: throw; default: break; } } break; } // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("connected", null); readBuffer = new byte[64 * 1024]; if (type == ConnectType.WebSocket) { CoreApplication.Properties.Add("clientSocket", streamWebSocket); // Start a background task to continuously read for incoming data Task receiving = Task.Factory.StartNew(ReceiveDataLoop, streamWebSocket.InputStream.AsStreamForRead(), TaskCreationOptions.LongRunning); } else { CoreApplication.Properties.Add("clientSocket", socket); // Start a background task to continuously read for incoming data Task receiving = Task.Factory.StartNew(ReceiveDataLoop, socket.InputStream.AsStreamForRead(), TaskCreationOptions.LongRunning); } this._timer = ThreadPoolTimer.CreatePeriodicTimer(_timerEvent, TimeSpan.FromSeconds(KeepAliveTimeout)); return(true); }
public void ConstructorTests_WebSocketError_NativeError_Success(int nativeError, WebSocketError error, int expectedHResult) { var wse = new WebSocketException(error, nativeError); Assert.Equal(expectedHResult, wse.HResult); Assert.Equal(error, wse.WebSocketErrorCode); Assert.NotEqual("", wse.Message); Assert.Null(wse.InnerException); }
public WebSocketException(int nativeError, Exception innerException) : base(SR.GetString(SR.net_WebSockets_Generic), innerException) { m_WebSocketErrorCode = !WebSocketProtocolComponent.Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success; this.SetErrorCodeOnError(nativeError); }
public void ConstructorTests_WebSocketError_NativeError_Message_Exception_Success(int nativeError, WebSocketError error, int expectedHResult) { const string Message = "Message"; var inner = new Exception(); var wse = new WebSocketException(error, nativeError, Message, inner); Assert.Equal(expectedHResult, wse.HResult); Assert.Equal(error, wse.WebSocketErrorCode); Assert.Equal(Message, wse.Message); Assert.Same(inner, wse.InnerException); }
public WebSocketException(WebSocketError error, string message, Exception innerException) : base(message, innerException) { _webSocketErrorCode = error; }
void AssertWebSocketException (AggregateException e, WebSocketError error, Type inner = null) { var wsEx = e.InnerException as WebSocketException; Console.WriteLine (e.InnerException.ToString ()); Assert.IsNotNull (wsEx, "Not a websocketexception"); Assert.AreEqual (error, wsEx.WebSocketErrorCode); if (inner != null) { Assert.IsNotNull (wsEx.InnerException); Assert.IsTrue (inner.IsInstanceOfType (wsEx.InnerException)); } }
public WebSocketException(int nativeError, string message) : base(nativeError, message) { _webSocketErrorCode = !Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success; SetErrorCodeOnError(nativeError); }
public WebSocketException(int nativeError, string message) : base(nativeError, message) { _webSocketErrorCode = !Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success; SetErrorCodeOnError(nativeError); }
public WebSocketException(int nativeError, Exception innerException) : base(SR.net_WebSockets_Generic, innerException) { _webSocketErrorCode = !Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success; SetErrorCodeOnError(nativeError); }
public WebSocketException(WebSocketError error, int nativeError, string message, Exception innerException) : base(message, innerException) { _webSocketErrorCode = error; SetErrorCodeOnError(nativeError); }
private void Connection_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { try { var task = new Task <DataReader>(new Func <DataReader>(args.GetDataReader)); task.Start(); var result = task.Wait(5000); var dr = result ? task.Result : null; if (!result) { throw new Exception("Timeout while reading response, possible disconnect"); } using (dr) { dr.UnicodeEncoding = UnicodeEncoding.Utf8; var message = dr.ReadString(dr.UnconsumedBufferLength); var obj = JsonConvert.DeserializeObject <dynamic>(message); var id = (string)obj.id; var type = (string)obj.type; TaskCompletionSource <dynamic> taskCompletion; if (type == "registered") { if (_tokens.TryRemove(id, out taskCompletion)) { var key = (string)JObject.Parse(message)["payload"]["client-key"]; taskCompletion.TrySetResult(new { clientKey = key }); } } else if (_tokens.TryGetValue(id, out taskCompletion)) { if (id == "register_0") { return; } if (obj.type == "error") { taskCompletion.SetException(new Exception(obj.error?.ToString())); } //else if (args.Cancelled) //{ // taskSource.SetCanceled(); //} taskCompletion.TrySetResult(obj.payload); if (_callbacks.TryGetValue(id, out Func <dynamic, bool> callback)) { try { callback(obj.payload); } catch (Exception callbackException) { Logger.Error($"Connection_MessageReceived: the callback threw an exception: {callbackException.ToLogString()}"); } } } } } catch (Exception ex) { var status = WebSocketError.GetStatus(ex.GetBaseException().HResult); Logger.Error($"Connection_MessageReceived: status: {status}, exception: {ex.ToLogString()}"); SetExceptionOnAllTokens(ex); ConnectionClosed = true; _messageWriter?.Dispose(); } }
public WebSocketException (WebSocketError error, int nativeError) : this (error, nativeError, DefaultMessage, null) { }
public async Task ReceiveAsync_MultipleOutstandingReceiveOperations_Throws(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); Task[] tasks = new Task[2]; await cws.SendAsync( WebSocketData.GetBufferFromText(".delay5sec"), WebSocketMessageType.Text, true, cts.Token); var recvBuffer = new byte[100]; var recvSegment = new ArraySegment <byte>(recvBuffer); try { for (int i = 0; i < tasks.Length; i++) { tasks[i] = cws.ReceiveAsync(recvSegment, cts.Token); } Task.WaitAll(tasks); Assert.Equal(WebSocketState.Open, cws.State); } catch (AggregateException ag) { foreach (var ex in ag.InnerExceptions) { if (ex is InvalidOperationException) { Assert.Equal( ResourceHelper.GetExceptionMessage( "net_Websockets_AlreadyOneOutstandingOperation", "ReceiveAsync"), ex.Message); Assert.Equal(WebSocketState.Aborted, cws.State); } else if (ex is WebSocketException) { // Multiple cases. Assert.Equal(WebSocketState.Aborted, cws.State); WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode; Assert.True( (errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success), "WebSocketErrorCode"); } else if (ex is OperationCanceledException) { Assert.Equal(WebSocketState.Aborted, cws.State); } else { Assert.True(false, "Unexpected exception: " + ex.Message); } } } } }
public WebSocketException (WebSocketError error, int nativeError, Exception innerException) : this (error, nativeError, DefaultMessage, innerException) { }
public WebSocketException(WebSocketError error, int nativeError, string message, Exception innerException) : base(message, innerException) { _webSocketErrorCode = error; SetErrorCodeOnError(nativeError); }
public WebSocketException (WebSocketError error, string message, Exception innerException) : this (error, -1, message, innerException) { }
private WebSocketException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { _webSocketErrorCode = (WebSocketError)serializationInfo.GetInt32(nameof(WebSocketErrorCode)); }
public WebSocketException(WebSocketError error, string message) : base(message) { m_WebSocketErrorCode = error; }
public WebSocketException(WebSocketError error) : this(error, GetErrorMessage(error)) { }
public WebSocketException(WebSocketError error, string message, Exception innerException) : base(message, innerException) { m_WebSocketErrorCode = error; }
public WebSocketException(WebSocketError error, string message) : base(message) { _webSocketErrorCode = error; }
public WebSocketException(int nativeError, Exception innerException) : base(SR.GetString(SR.net_WebSockets_Generic), innerException) { m_WebSocketErrorCode = !WebSocketProtocolComponent.Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success; this.SetErrorCodeOnError(nativeError); }
public WebSocketException(WebSocketError error, Exception innerException) : this(error, GetErrorMessage(error), innerException) { }
public WebSocketException(WebSocketError error, int nativeError, string message) : base(message) { m_WebSocketErrorCode = error; this.SetErrorCodeOnError(nativeError); }
public WebSocketException(WebSocketError error, string message, Exception innerException);