internal virtual async void BindAsync(StreamSocket socketStream) { this.ConnectionStatus = ConnectionStatus.Connecting; this.streamSocket = socketStream; try { cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(socketObject.CancellationTokenSource.Token); using (DataReader dataReader = new DataReader(socketStream.InputStream)) { CancellationToken cancellationToken = cancellationTokenSource.Token; //setup cancellationToken.ThrowIfCancellationRequested(); dataReader.InputStreamOptions = InputStreamOptions.Partial; this.ConnectionStatus = ConnectionStatus.Connected; //Send a Hello message across await Parse("Hello" + Environment.NewLine).ConfigureAwait(false); loadOperation = dataReader.LoadAsync(bufferSize); uint bytesAvailable = await loadOperation.AsTask(cancellationToken).ConfigureAwait(false); while (bytesAvailable > 0 && loadOperation.Status == Windows.Foundation.AsyncStatus.Completed) { await streamAccess.WaitAsync().ConfigureAwait(false); if (streamWritePosition == streamReadPosition) { streamReadPosition = 0; streamWritePosition = 0; memoryStream.SetLength(0); } memoryStream.Position = streamWritePosition; byte[] buffer = dataReader.ReadBuffer(bytesAvailable).ToArray(); await memoryStream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false); streamWritePosition = memoryStream.Position; streamAccess.Release(); await ParseStream().ConfigureAwait(false); bytesRead += bytesAvailable; loadOperation = dataReader.LoadAsync(bufferSize); bytesAvailable = await loadOperation.AsTask(cancellationToken).ConfigureAwait(false); } dataReader.DetachBuffer(); dataReader.DetachStream(); } } catch (TaskCanceledException) { } catch (Exception exception) { socketObject.ConnectionStatus = ConnectionStatus.Failed; Debug.WriteLine(string.Format("Error receiving data: {0}", exception.Message)); } await socketObject.CloseSession(this.sessionId).ConfigureAwait(false); this.ConnectionStatus = ConnectionStatus.Disconnected; this.OnMessageReceived -= socketObject.Instance_OnMessageReceived; }
public override async Task CloseChannel(Guid sessionId) { await instance.CloseSession(sessionId).ConfigureAwait(false); }