/// <summary> /// Receives a single message from the service. /// </summary> /// <param name="webSocket">The connected WebSocket on which to listen for the message.</param> /// <param name="requestId">The request ID associated with the message.</param> /// <param name="token">A task cancellation token.</param> /// <returns> /// A Task representing the asynchronous operation whose result will contain the message /// received from the service upon task completion. /// </returns> private async Task <SpeechServiceMessage> ReceiveMessageAsync(WebSocket webSocket, string requestId, CancellationToken token) { WebSocketReceiveResult result = null; ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[8192]); using (var stream = new MemoryStream()) { // Read incoming message into a MemoryStream (potentially in multiple chunks) do { try { result = await webSocket.ReceiveAsync(buffer, token); } catch (OperationCanceledException) { continue; } stream.Write(buffer.Array, buffer.Offset, result.Count); }while (result != null && !result.EndOfMessage); token.ThrowIfCancellationRequested(); stream.Seek(0, SeekOrigin.Begin); if (result.MessageType == WebSocketMessageType.Text) { using (var reader = new StreamReader(stream, Encoding.UTF8)) { var message = reader.ReadToEnd(); var speechServiceMessage = SpeechServiceMessage.Deserialize(message); if (speechServiceMessage.RequestId == requestId) { return(speechServiceMessage); } } } else if (result.MessageType == WebSocketMessageType.Close) { if (webSocket.CloseStatus.HasValue) { // Translate the close status to a ConversationError and raise it this.RaiseTranslatedError(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription); } return(null); } // No other message types are supported throw new NotSupportedException(); } }
/// <summary> /// Sends a message to the service. /// </summary> /// <param name="message">The message to send.</param> /// <param name="requestId">The request id associated with the message.</param> /// <param name="token">A task cancellation token.</param> /// <returns>A Task representing the asynchronous operation.</returns> private async Task SendMessageAsync(SpeechServiceMessage message, string requestId, CancellationToken token) { message.Headers["X-Timestamp"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffK"); message.Headers["X-RequestId"] = requestId; await this.webSocket.SendAsync( new ArraySegment <byte>(message.GetBytes()), message is SpeechServiceBinaryMessage?WebSocketMessageType.Binary : WebSocketMessageType.Text, true, token); }