async void OnLoaded(object sender, RoutedEventArgs e) { this.receiveSocket = new TcpListener( IPAddress.Loopback, 8888); this.receiveSocket.Start(); // Accept one incoming connection and open up a stream over it for reading. using (var socket = await this.receiveSocket.AcceptSocketAsync()) using (var receiveStream = new NetworkStream(socket)) { var sizeBuffer = new byte[sizeof(ulong)]; // We loop for as long as that connection works for us and we make no // attempt to recover if we have a read failure or similar. // // Note - because BitmapDecoder.CreateAsync() can take a stream without // having to specify a size, it seems like I can just feed the network // stream here straight into my function CreateSoftwareBitmapFromStreamAsync // but that won't work because BitmapDecoder wants a stream that it can // seek which the NetworkStream here won't be. Hence, we read the image // of the network into a MemoryStream and that means we need to know how // much we need to read and that means writing the size of the image down // the wire first. while (true) { // Read the size of the incoming image from the stream. var readCount = await receiveStream.ReadAsync(sizeBuffer, 0, sizeof(ulong)); if (readCount == sizeof(ulong)) { // How big does the image say it is? var imageSize = BitConverter.ToUInt64(sizeBuffer, 0); // Make a memory stream that's big enough to store the incoming image. using (var imageStream = new MemoryStream((int)imageSize)) { // Copy from the network into that memory stream. await RandomAccessStream.CopyAsync( receiveStream.AsInputStream(), imageStream.AsOutputStream(), imageSize); // Create an image source (this is a XAML thing) in order to be able // to put the image on the screen. var imageSource = await CreateSoftwareBitmapSourceFromStreamAsync( imageStream.AsRandomAccessStream()); // We are not on the UI thread so need to switch to do this. await this.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { // And put the image on the screen. ReplaceImageSoftwareBitmapSource(this.destImage, imageSource); } ); } } } } }