/// <summary> /// Opens the websocket connection and sends the CONNECT message. /// </summary> /// <returns><System.Boolean> true if successful.</returns> public async Task <bool> ConnectAsync(Action <string> errorsEventHandler) { const string WEBSOCKETPATH = "/w/messages/websocket"; // Based on https://docs.nem.io/en/nem-dev-basics-docker/blockchain-monitoring await ClientWs.ConnectAsync(new Uri(string.Concat("ws://", Domain, ":", Port, WEBSOCKETPATH)), CancellationToken.None); if (ClientWs.State != WebSocketState.Open) { return(false); } // Send CONNECT StompMessage connect = new StompMessage(StompMessage.ClientCommands.CONNECT); // Set message headers, might not be needed //connect["accept-version"] = "1.1,1.0"; //connect["heart-beat"] = "10000, 10000"; // out, in await SendAsync(connect); // Read the answer from the server StompMessage connectedMsg = StompMessage.Deserialize(await ReadSocketAsync()); if (connectedMsg.Command != StompMessage.ServerResponses.CONNECTED) { return(false); } // Subscribe to errors channel await SubscribeToErrorsAsync(errorsEventHandler); // Start the Loop to read answers Task loop = LoopReadStompMsgsAsync(); // Explicitely not using await, to allow the Loop to run asynchronously without waiting for it to complete! return(true); }
/// <summary> /// Loop to read Stomp messages from the websocket and call appropriate actions. /// </summary> private async Task LoopReadStompMsgsAsync() { while (ClientWs.State == WebSocketState.Open) // Infinite loop for as long as we are running with an open socket { var msg = await ReadSocketAsync(); StompMessage stompMsg = StompMessage.Deserialize(msg); switch (stompMsg.Command) { case StompMessage.ServerResponses.ERROR: this.OnErrorEventHandler?.Invoke(stompMsg.Body); break; case StompMessage.ServerResponses.MESSAGE: ProcessReceivedMessage(stompMsg.GetDestination(), stompMsg.Body); break; default: // throw exception? Debug.WriteLine("Received STOMP Message with an unsupported Command: " + stompMsg); break; } } }