Example #1
0
        /// <summary>
        /// This is the click handler for the 'Copy Strings' button.  Here we will parse the
        /// strings contained in the ElementsToWrite text block, write them to a stream using
        /// DataWriter, retrieve them using DataReader, and output the results in the
        /// ElementsRead text block.
        /// </summary>
        /// <param name="sender">Contains information about the button that fired the event.</param>
        /// <param name="e">Contains state information and event data associated with a routed event.</param>
        private async void TransferData(object sender, RoutedEventArgs e)
        {
            // Initialize the in-memory stream where data will be stored.
            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                // Create the data writer object backed by the in-memory stream.
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream))
                {
                    dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataWriter.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Write each element separately.
                    foreach (string inputElement in inputElements)
                    {
                        uint inputElementSize = dataWriter.MeasureString(inputElement);
                        dataWriter.WriteUInt32(inputElementSize);
                        dataWriter.WriteString(inputElement);
                    }

                    // Send the contents of the writer to the backing stream.
                    await dataWriter.StoreAsync();

                    // For the in-memory stream implementation we are using, the flushAsync call is superfluous,
                    // but other types of streams may require it.
                    await dataWriter.FlushAsync();

                    // In order to prolong the lifetime of the stream, detach it from the DataWriter so that it
                    // will not be closed when Dispose() is called on dataWriter. Were we to fail to detach the
                    // stream, the call to dataWriter.Dispose() would close the underlying stream, preventing
                    // its subsequent use by the DataReader below.
                    dataWriter.DetachStream();
                }

                // Create the input stream at position 0 so that the stream can be read from the beginning.
                stream.Seek(0);
                using (var dataReader = new Windows.Storage.Streams.DataReader(stream))
                {
                    // The encoding and byte order need to match the settings of the writer we previously used.
                    dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataReader.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Once we have written the contents successfully we load the stream.
                    await dataReader.LoadAsync((uint)stream.Size);

                    var receivedStrings = "";

                    // Keep reading until we consume the complete stream.
                    while (dataReader.UnconsumedBufferLength > 0)
                    {
                        // Note that the call to readString requires a length of "code units" to read. This
                        // is the reason each string is preceded by its length when "on the wire".
                        uint bytesToRead = dataReader.ReadUInt32();
                        receivedStrings += dataReader.ReadString(bytesToRead) + "\n";
                    }

                    // Populate the ElementsRead text block with the items we read from the stream.
                    ElementsRead.Text = receivedStrings;
                }
            }
        }
Example #2
0
        private async void      OnConnection(Windows.Networking.Sockets.StreamSocketListener sender,
                                             Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.LogError("New client" + sender.Information.LocalPort);

            var reader = new Windows.Storage.Streams.DataReader(args.Socket.InputStream);

            try
            {
                while (true)
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));

                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Read the string.
                    uint stringLength       = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);

                    if (stringLength != actualStringLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal
                    // the text back to the UI thread.
                    //NotifyUserFromAsyncThread(
                    //	String.Format("Received data: \"{0}\"", reader.ReadString(actualStringLength)),
                    //	NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (Windows.Networking.Sockets.SocketError.GetStatus(ex.HResult) == Windows.Networking.Sockets.SocketErrorStatus.Unknown)
                {
                    throw;
                }
            }
        }
Example #3
0
        // Read out and print the message received from the socket.
        private async void StartReader(Windows.Networking.Sockets.StreamSocket socket,
                                       Windows.Storage.Streams.DataReader reader)
        {
            try
            {
                uint bytesRead = await reader.LoadAsync(sizeof(uint));

                if (bytesRead > 0)
                {
                    uint strLength = (uint)reader.ReadUInt32();
                    bytesRead = await reader.LoadAsync(strLength);

                    if (bytesRead > 0)
                    {
                        String message = reader.ReadString(strLength);
                        WriteMessageText("Received message: " + message + "\n");
                        StartReader(socket, reader); // Start another reader
                    }
                    else
                    {
                        WriteMessageText("The peer app closed the socket\n");
                        reader.Dispose();
                        CloseSocket();
                    }
                }
                else
                {
                    WriteMessageText("The peer app closed the socket\n");
                    reader.Dispose();
                    CloseSocket();
                }
            }
            catch
            {
                WriteMessageText("The peer app closed the socket\n");
                reader.Dispose();
                CloseSocket();
            }
        }
        /// <summary>
        /// This is the click handler for the 'Copy Strings' button.  Here we will parse the
        /// strings contained in the ElementsToWrite text block, write them to a stream using
        /// DataWriter, retrieve them using DataReader, and output the results in the
        /// ElementsRead text block.
        /// </summary>
        /// <param name="sender">Contains information about the button that fired the event.</param>
        /// <param name="e">Contains state information and event data associated with a routed event.</param>
        private async void TransferData(object sender, RoutedEventArgs e)
        {
            // Initialize the in-memory stream where data will be stored.
            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                // Create the data writer object backed by the in-memory stream.
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream))
                {
                    dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Write each element separately.
                    foreach (string inputElement in inputElements)
                    {
                        uint inputElementSize = dataWriter.MeasureString(inputElement);
                        dataWriter.WriteUInt32(inputElementSize);
                        dataWriter.WriteString(inputElement);
                    }

                    // Send the contents of the writer to the backing stream.
                    await dataWriter.StoreAsync();

                    // For the in-memory stream implementation we are using, the flushAsync call is superfluous,
                    // but other types of streams may require it.
                    await dataWriter.FlushAsync();

                    // In order to prolong the lifetime of the stream, detach it from the DataWriter so that it 
                    // will not be closed when Dispose() is called on dataWriter. Were we to fail to detach the 
                    // stream, the call to dataWriter.Dispose() would close the underlying stream, preventing 
                    // its subsequent use by the DataReader below.
                    dataWriter.DetachStream();
                }

                // Create the input stream at position 0 so that the stream can be read from the beginning.
                stream.Seek(0);
                using (var dataReader = new Windows.Storage.Streams.DataReader(stream))
                {
                    // The encoding and byte order need to match the settings of the writer we previously used.
                    dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataReader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Once we have written the contents successfully we load the stream.
                    await dataReader.LoadAsync((uint)stream.Size);

                    var receivedStrings = "";

                    // Keep reading until we consume the complete stream.
                    while (dataReader.UnconsumedBufferLength > 0)
                    {
                        // Note that the call to readString requires a length of "code units" to read. This
                        // is the reason each string is preceded by its length when "on the wire".
                        uint bytesToRead = dataReader.ReadUInt32();
                        receivedStrings += dataReader.ReadString(bytesToRead) + "\n";
                    }

                    // Populate the ElementsRead text block with the items we read from the stream.
                    ElementsRead.Text = receivedStrings;
                }
            }
        }