コード例 #1
0
 private async Task<string> DoCommand(string command)
 {
     StringBuilder strBuilder = new StringBuilder();
     using (StreamSocket clientSocket = new StreamSocket())
     {
         await clientSocket.ConnectAsync(new HostName("192.168.9.108"),  "9001");
         using (DataWriter writer = new DataWriter(clientSocket.OutputStream))
         {
             writer.WriteString(command);
             await writer.StoreAsync();
             writer.DetachStream();
         }
         using (DataReader reader = new DataReader(clientSocket.InputStream))
         {
             reader.InputStreamOptions = InputStreamOptions.Partial;
             await reader.LoadAsync(8192);
             while (reader.UnconsumedBufferLength > 0)
             {
                 strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
                 await reader.LoadAsync(8192);
             }
             reader.DetachStream();
         }
     }
     return (strBuilder.ToString());
 }
コード例 #2
0
 private async Task<RfidReaderResult> Read()
 {
     RfidReaderResult retvalue = new RfidReaderResult();
     var dataReader = new DataReader(_rfidReader.InputStream);
     try
     {
         SetStatus("Awaiting Data from RFID Reader");
         var numBytesRecvd = await dataReader.LoadAsync(1024);
         retvalue.Result = new byte[numBytesRecvd];
         if (numBytesRecvd > 0)
         {
             SetStatus("Data successfully read from RFID Reader");
             dataReader.ReadBytes(retvalue.Result);
             retvalue.IsSuccessful = true;
             retvalue.Message = "Data successfully read from RFID Reader";
         }
     }
     catch (Exception ex)
     {
         retvalue.IsSuccessful = false;
         retvalue.Message = ex.Message;
     }
     finally
     {
         if (dataReader != null)
         {
             dataReader.DetachStream();
             dataReader = null;
         }
     }
     return retvalue;
 }
コード例 #3
0
ファイル: TCPManager.cs プロジェクト: xiaozhuchacha/AOG_AR
    private async void read_data()
    {
        ifListening = true;
        // int read_msg_counter = 2;
        using (var reader = new Windows.Storage.Streams.DataReader(streamSocket.InputStream)){
            reader.InputStreamOptions = Windows.Storage.Streams.InputStreamOptions.ReadAhead;
            reader.UnicodeEncoding    = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            reader.ByteOrder          = Windows.Storage.Streams.ByteOrder.LittleEndian;

            await reader.LoadAsync(4);

            while (reader.UnconsumedBufferLength > 0)
            {
                // read_msg_counter--;
                int bytesToRerad = reader.ReadInt32();
                // Debug.Log("bytes to read: " + bytesToRerad);
                if (bytesToRerad <= 0)
                {
                    return;
                }
                await reader.LoadAsync(Convert.ToUInt32(bytesToRerad));

                byte[] buffer = new byte[bytesToRerad];
                reader.ReadBytes(buffer);
                processReceivedData(buffer, bytesToRerad);

                await reader.LoadAsync(4);
            }

            reader.DetachStream();
        }
        ifListening = false;
    }
コード例 #4
0
ファイル: LogTrace.cs プロジェクト: joelong01/CircleCribbage
        public async Task <string> ReadLogFile(string fileName)
        {
            if (fileName != this.FQP)
            {
                int index = fileName.IndexOf(DIRECTORY_NAME);
                fileName = fileName.Substring(index);
                var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

                if (file == null)
                {
                    return("");
                }

                return(await Windows.Storage.FileIO.ReadTextAsync(file));
            }

            if (_logFile != null)
            {
                using (var inputStream = _stream.GetInputStreamAt(0))
                {
                    Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(inputStream);
                    await reader.LoadAsync((uint)_stream.Size);

                    string data = reader.ReadString((uint)_stream.Size);
                    reader.DetachStream();
                    return(data);
                }
            }

            return("");
        }
コード例 #5
0
ファイル: IOStream.cs プロジェクト: nghia2080/CProject
        /// <summary>
        /// Read string content from file.
        /// </summary>
        /// <param name="path">Location of file, separate by //.</param>
        /// <param name="rootFolder"> </param>
        /// <returns>Content of file.</returns>
        public async Task<string> ReadFromFileAsync(string path, StorageFolder rootFolder = null)
        {
            if (path == null)
            {
                return null;
            }

            try
            {
                var file = await GetFileToReadAsync(path, rootFolder);

                if (file == null)
                {
                    return null;
                }

                var readStream = await file.OpenAsync(FileAccessMode.Read);

                var inputStream = readStream.GetInputStreamAt(0);
                var dataReader = new DataReader(inputStream);

                var numBytesLoaded = await dataReader.LoadAsync((uint)readStream.Size);
                var content = dataReader.ReadString(numBytesLoaded);
                dataReader.DetachStream();
                dataReader.Dispose();
                inputStream.Dispose();
                readStream.Dispose();

                return content;
            }
            catch
            {
                return null;
            }
        }
コード例 #6
0
ファイル: StreamUtils.cs プロジェクト: ababilone/maxmanager
		public static async Task<string> ReadLine(this IInputStream inputStream)
		{
			using (var dataReader = new DataReader(inputStream))
			{
				var line = await dataReader.ReadLine();
				dataReader.DetachStream();
				return line;
			}
		}
コード例 #7
0
        public async Task <T> LoadASync(string FileName)
        {
            FileName = FileName + ".xml";
            try
            {
                StorageFile   file   = null;
                StorageFolder folder = GetFolder(storageType);
                file = await folder.GetFileAsync(FileName);

                //using (var readStream = await file.OpenAsync(FileAccessMode.Read))
                //{
                //    Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(readStream);

                //    await reader.LoadAsync((uint)readStream.Size);
                //    string data = reader.ReadString((uint)readStream.Size);

                //    if (data == null)
                //    {
                //    }
                //}


                using (var readStream = await file.OpenAsync(FileAccessMode.Read))
                {
                    //Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;
                    //return (T)serializer.Deserialize(inStream);

                    var inStream = readStream.GetInputStreamAt(0);
                    Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(inStream);
                    await reader.LoadAsync((uint)readStream.Size);

                    string data = reader.ReadString((uint)readStream.Size);
                    reader.DetachStream();

                    MemoryStream ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(data));
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                    T result = (T)ser.ReadObject(ms);
                    return(result);
                }
            }
            catch (FileNotFoundException)
            {
                //file not existing is perfectly valid so simply return the default
                return(default(T));
                //throw;
            }
            catch (Exception)
            {
                //Unable to load contents of file
                throw;
            }
        }
コード例 #8
0
 internal static async Task<string> ReadTextAsync(this StorageFile file)
 {
     using (var fs = await file.OpenAsync(FileAccessMode.Read))
     {
         using (var inStream = fs.GetInputStreamAt(0))
         {
             using (var dataReader = new DataReader(inStream))
             {
                 await dataReader.LoadAsync((uint)fs.Size);
                 var data = dataReader.ReadString((uint)fs.Size);
                 dataReader.DetachStream();
                 return data;
             }
         }
     }
 }
コード例 #9
0
 /// <summary>
 /// Копировать из RT потока в .NET поток с прогрессом.
 /// </summary>
 /// <param name="src">Исхоный поток.</param>
 /// <param name="outStream">Поток результата.</param>
 /// <param name="progress">Прогресс.</param>
 /// <param name="token">Токен отмены.</param>
 /// <param name="bufferSize">Размер буфера.</param>
 /// <returns>Таск.</returns>
 public static async Task CopyToNetStreamWithProgress(this IInputStream src, Stream outStream, IProgress<ulong> progress, CancellationToken token, uint bufferSize = 16384)
 {
     ulong totalRead = 0;
     using (var rd = new DataReader(src))
     {
         progress.Report(0);
         do {
             token.ThrowIfCancellationRequested();
             var r = await rd.LoadAsync(bufferSize);
             totalRead += r;
             progress.Report(totalRead);
             if (r <= 0) break;
             var buf = new byte[r];
             rd.ReadBytes(buf);
             await outStream.WriteAsync(buf, 0, (int)r, token);
         } while (true);
         rd.DetachStream();
     }
 }
コード例 #10
0
        public async void StartReader(ConnectedPeer connectedPeer)
        {
            try
            {
                using (var socketReader = new Windows.Storage.Streams.DataReader(connectedPeer._socket.InputStream))
                {
                    // Read the message sent by the remote peer
                    uint bytesRead = await socketReader.LoadAsync(sizeof(uint));

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

                        if (bytesRead > 0)
                        {
                            String message = socketReader.ReadString(strLength);
                            OnRaiseMessageEvent(new MessageEventArgs("Got message: " + message));
                            StartReader(connectedPeer); // Start another reader
                        }
                        else
                        {
                            OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket"));
                        }
                    }
                    else
                    {
                        OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket"));
                    }

                    socketReader.DetachStream();
                }
            }
            catch (Exception e)
            {
                if (!connectedPeer._socketClosed)
                {
                    OnRaiseSocketErrorEvent(new SocketEventArgs("Reading from socket failed: " + e.Message));
                }
            }
        }
コード例 #11
0
        public static async Task<string> ReadFromFile(
            string fileName,
            StorageFolder folder = null)
        {
            folder = folder ?? ApplicationData.Current.LocalFolder;
            var file = await folder.GetFileAsync(fileName);

            using (var fs = await file.OpenAsync(FileAccessMode.Read))
            {
                using (var inStream = fs.GetInputStreamAt(0))
                {
                    using (var reader = new DataReader(inStream))
                    {
                        await reader.LoadAsync((uint)fs.Size);
                        string data = reader.ReadString((uint)fs.Size);
                        reader.DetachStream();
                        return data;
                    }
                }
            }
        }
コード例 #12
0
        public static async Task<DateTimeOffset?> RetrieveLinkerTimestamp(Assembly assembly)
        {
            var pkg = Windows.ApplicationModel.Package.Current;
            if (null == pkg)
            {
                return null;
            }

            var assemblyFile = await pkg.InstalledLocation.GetFileAsync(assembly.ManifestModule.Name);
            if (null == assemblyFile)
            {
                return null;
            }

            using (var stream = await assemblyFile.OpenSequentialReadAsync())
            {
                using (var reader = new DataReader(stream))
                {
                    const int PeHeaderOffset = 60;
                    const int LinkerTimestampOffset = 8;

                    //read first 2048 bytes from the assembly file.
                    byte[] b = new byte[2048];
                    await reader.LoadAsync((uint)b.Length);
                    reader.ReadBytes(b);
                    reader.DetachStream();

                    //get the pe header offset
                    int i = System.BitConverter.ToInt32(b, PeHeaderOffset);

                    //read the linker timestamp from the PE header
                    int secondsSince1970 = System.BitConverter.ToInt32(b, i + LinkerTimestampOffset);

                    var dt = new DateTimeOffset(1970, 1, 1, 0, 0, 0, DateTimeOffset.Now.Offset) + DateTimeOffset.Now.Offset;
                    return dt.AddSeconds(secondsSince1970);
                }
            }
        }
コード例 #13
0
ファイル: MainPage.xaml.cs プロジェクト: Cocotus/kinect
		private async void ValidateAndLoadSketch()
		{
			if (!_isJavascriptReady || !_isBrowserLoaded)
				return;

			var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///sketch.pde", UriKind.RelativeOrAbsolute));

			using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
			{
				using (var inStream = fs.GetInputStreamAt(0))
				{
					using (var dataReader = new DataReader(inStream))
					{
						await dataReader.LoadAsync((uint)fs.Size);
						_sketchText = dataReader.ReadString((uint)fs.Size);
						dataReader.DetachStream();
					}
				}
			}

			if (_sketchText != "")
				Browser.InvokeScript("loadSketch", new[] { _sketchText });
		}
コード例 #14
0
ファイル: MainPage.xaml.cs プロジェクト: kiewic/Projects
        //
        // TCP server and TCP client common.
        //

        private async Task<string> ReadUntilCrLf(IInputStream inputStream, TextBlock outputTextBlock)
        {
            DataReader reader = new DataReader(inputStream);
            reader.InputStreamOptions = InputStreamOptions.Partial;

            string message = "";
            while (!message.EndsWith("\r\n"))
            {
                // Read bytes in multiples of 16, to make it more fun.
                // If the socket is closed while we are reading, the "The I/O operation has
                // been aborted because of either a thread exit or an application request.
                // (Exception from HRESULT: 0x800703E3)" exception is thrown.
                uint bytesRead = await reader.LoadAsync(16);
                if (bytesRead == 0)
                {
                    // If bytesRead is zero, incoming stream was closed.
                    DisplayOutput(outputTextBlock, "The connection was closed by remote host.");
                    break;
                }
                // TODO: Why DataReader doesn't have ReadChar()?
                message += reader.ReadString(bytesRead);
            }

            // Do not use Dispose(). If used, streams cannot be used anymore.
            //reader.Dispose();

            // Without this, the DataReader destructor will close the stream, and closing the
            // stream might set the FIN control bit.
            reader.DetachStream();

            return message;
        }
コード例 #15
0
ファイル: Connection.cs プロジェクト: opengd/Chimney
        public static async Task<string> Recive(StreamSocket streamSocket, List<string> orstarts, List<string> orends, List<string> andstarts, List<string> andends)
        {
            string returnString = string.Empty;

            try
            {
                using (var dataReader = new DataReader(streamSocket.InputStream))
                {
                    dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataReader.InputStreamOptions = InputStreamOptions.Partial;

                    var end = false;

                    while (!end && await dataReader.LoadAsync(64000) != 0)
                    {
                        string readString;
                        var buffer = dataReader.ReadBuffer(dataReader.UnconsumedBufferLength);
                        using (var dr = DataReader.FromBuffer(buffer))
                        {
                            var bytes1251 = new Byte[buffer.Length];
                            dr.ReadBytes(bytes1251);

                            readString = Encoding.GetEncoding("UTF-8").GetString(bytes1251, 0, bytes1251.Length);
                        }

                        if (!string.IsNullOrEmpty(readString))
                            returnString += readString;

                        if (readString == null)
                        {
                            end = true;
                        }
                        else if (orstarts.FirstOrDefault(o => returnString.StartsWith(o)) != null)
                        {
                            end = true;
                        }
                        else if (orends.FirstOrDefault(o => returnString.EndsWith(o)) != null)
                        {
                            end = true;
                        }
                        else if (andstarts.FirstOrDefault(o => returnString.StartsWith(o)) != null
                                && andends.FirstOrDefault(o => returnString.EndsWith(o)) != null)
                        {
                            end = true;
                        }
                    }

                    dataReader.DetachStream();
                }
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex.Message);
                returnString = string.Empty;
            }

            return returnString;
        }
コード例 #16
0
ファイル: Xmpp.cs プロジェクト: gchatapp/GchatWin
        public IAsyncOperation<string> Connect() {
            var window = CoreWindow.GetForCurrentThread();

            return Task.Run<string>(async () =>
            {
                try
                {
                    var socket = this.socket = new Windows.Networking.Sockets.StreamSocket();

                    await socket.ConnectAsync(new HostName("talk.google.com"), "5222", SocketProtectionLevel.PlainSocket);

                    await log(window, "connected!");

                    reader = new DataReader(socket.InputStream);
                    writer = new DataWriter(socket.OutputStream);

                    reader.InputStreamOptions = InputStreamOptions.Partial;

                    Write("<?xml version='1.0'?>\n<stream:stream to='" + server + "' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");

                    xmlStream = new XmlStream();
                    bool shouldRead = true;

                    xmlStream.SetCallback(async (promptRead, data) => {
                        await log(window, "data " + data);

                        if (promptRead)
                        {
                            if (shouldRead)
                            {
                                await log(window, "prompt read");

                                await reader.LoadAsync(4096);
                                var buffer = new byte[reader.UnconsumedBufferLength];
                                reader.ReadBytes(buffer);
                                await log(window, "in " + Encoding.UTF8.GetString(buffer, 0, buffer.Length));
                                xmlStream.Update(buffer, 0, buffer.Length);
                            }
                            else
                            {
                                await log(window, "read blocked");
                            }
                        }
                        else if (data.IndexOf("stream:features") != -1)
                        {
                            Write("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls' />");
                        }
                        else if (data.IndexOf("proceed") != -1)
                        {
                            await log(window, "SSL Strength: " + socket.Information.ProtectionLevel);

                            writer.DetachStream();
                            reader.DetachStream();

                            shouldRead = false;

                            if (server == "gmail.com")
                            {
                                await socket.UpgradeToSslAsync(SocketProtectionLevel.Ssl, new Windows.Networking.HostName("gmail.com"));
                            }
                            else
                            {
                                await socket.UpgradeToSslAsync(SocketProtectionLevel.Ssl, new Windows.Networking.HostName("talk.google.com"));
                            }

                            writer = new DataWriter(socket.OutputStream);
                            reader = new DataReader(socket.InputStream);

                            reader.InputStreamOptions = InputStreamOptions.Partial;

                            await log(window, "upgraded!");
                            await log(window, "SSL Strength: " + socket.Information.ProtectionLevel);

                            Write("<?xml version='1.0'?>\n<stream:stream to='" + server + "' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");

                            xmlStream.SetCallback(async (shouldRead2, data2) =>
                            {
                                await log(window, "data " + data2);

                                if (shouldRead2)
                                {
                                    await reader.LoadAsync(4096);
                                    var buffer = new byte[reader.UnconsumedBufferLength];
                                    reader.ReadBytes(buffer);
                                    await log(window, "in " + Encoding.UTF8.GetString(buffer, 0, buffer.Length));
                                    xmlStream.Update(buffer, 0, buffer.Length);
                                }
                                else if (data2.Contains("X-GOOGLE-TOKEN"))
                                {
                                    var token = Convert.ToBase64String(Encoding.UTF8.GetBytes('\x00' + this.username + '\x00' + this.auth));
                                    Write("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='X-GOOGLE-TOKEN'>" + token + "</auth>");
                                }
                                else if (data2.Contains("failure"))
                                {
                                    if (Disconnect != null) Disconnect(this, "auth failure");
                                }
                                else if (data2.Contains("success"))
                                {
                                    var messageEvent = Message;

                                    xmlStream.SetCallback(async (shouldRead3, data3) =>
                                    {
                                        if (shouldRead3)
                                        {
                                            await reader.LoadAsync(4096);
                                            var buffer = new byte[reader.UnconsumedBufferLength];
                                            reader.ReadBytes(buffer);
                                            await log(window, "in " + Encoding.UTF8.GetString(buffer, 0, buffer.Length));
                                            xmlStream.Update(buffer, 0, buffer.Length);
                                        }
                                        else if (data3 == "</stream:stream>")
                                        {
                                            await disconnect(window, "end of stream");
                                        }
                                        else if (!data3.StartsWith("<stream:stream"))
                                        {
                                            await message(window, data3);
                                        }
                                    });

                                    Write("<?xml version='1.0'?>\n<stream:stream to='" + server + "' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");
                                }
                                else if (!data2.StartsWith("<stream:stream"))
                                {
                                    await log(window, "Ummm not sure what to do with '" + data2 + "'. flee.");
                                    if (Disconnect != null) Disconnect(this, "protocol error");
                                }
                            });
                        }
                        else if (!data.StartsWith("<stream:stream"))
                        {
                            await log(window, "Ummm not sure what to do with '" + data + "'. flee.");
                            if (Disconnect != null) Disconnect(this, "protocol error");
                        }
                    });

                    return "ok";
                }
                catch (Exception e)
                {
                    return e.ToString();
                }
            }).AsAsyncOperation<string>();
        }
コード例 #17
0
        async private void recieveData()
        {
            StreamSocketListener listener = new StreamSocketListener();
            DataReader dr = new DataReader(newSocket.InputStream);
            dr.InputStreamOptions = InputStreamOptions.Partial;
            string msg = null;
            try
            {
                var count = await dr.LoadAsync(8192);
                if (count > 0)
                    msg = dr.ReadString(count);
            }
            catch { }
            dr.DetachStream();
            dr.Dispose();

            try
            {
                pdu2 = new PDU(msg);
                Execution temp = pdu2.Data.ToObject(typeof(Execution));
                _stepCollection.Clear();
                foreach (Step steps in temp.CurrentSequence.StepList)
                {
                    _stepCollection.Add(steps);
                }
            }

            catch (Exception e) { }
            Execution temp2 = pdu2.Data.ToObject(typeof(Execution));
            if (temp2.State == Execution.ExecutionStates.FINISHED || temp2.State == Execution.ExecutionStates.TERMINATED)
            {
                PDU pdu3 = new PDU(){
                    MessageID = (int)CommandMessageID.ResetTS,
                    MessageDescription = "Server please, reset TS",
                    MessageType = "Command",
                    Source = "Demo.Client",
                    Data = new JObject()
                };
                sendData(pdu3);
            } else { recieveData(); }
            
        }
コード例 #18
0
        /// <summary>
        /// Invoked when the socket listener accepts an incoming Bluetooth connection.
        /// </summary>
        /// <param name="sender">The socket listener that accepted the connection.</param>
        /// <param name="args">The connection accept parameters, which contain the connected socket.</param>
        private async void OnConnectionReceived(
            StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            // Don't need the listener anymore
            socketListener.Dispose();
            socketListener = null;

            try
            {
                socket = args.Socket;
            }
            catch (Exception e)
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage);
                });
                Disconnect();
                return;
            }

            // Note - this is the supported way to get a Bluetooth device from a given socket
            var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName);

            writer = new DataWriter(socket.OutputStream);
            var reader = new DataReader(socket.InputStream);
            bool remoteDisconnection = false;

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                rootPage.NotifyUser("Connected to Client: " + remoteDevice.Name, NotifyType.StatusMessage);
            });            

            // Infinite read buffer loop
            while (true)
            {
                try
                {
                    // Based on the protocol we've defined, the first uint is the size of the message
                    uint readLength = await reader.LoadAsync(sizeof(uint));

                    // Check if the size of the data is expected (otherwise the remote has already terminated the connection)
                    if (readLength < sizeof(uint))
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    uint currentLength = reader.ReadUInt32();

                    // Load the rest of the message since you already know the length of the data expected.  
                    readLength = await reader.LoadAsync(currentLength);

                    // Check if the size of the data is expected (otherwise the remote has already terminated the connection)
                    if (readLength < currentLength)
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    string message = reader.ReadString(currentLength);

                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        ConversationListBox.Items.Add("Received: " + message);
                    });
                }
                // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED).
                catch (Exception ex) when ((uint)ex.HResult == 0x800703E3)
                {
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        rootPage.NotifyUser("Client Disconnected Successfully", NotifyType.StatusMessage);
                    });
                    break;
                }
            }

            reader.DetachStream();
            if (remoteDisconnection)
            {
                Disconnect();
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    rootPage.NotifyUser("Client disconnected",NotifyType.StatusMessage);
                });
            }
        }
コード例 #19
0
ファイル: Files.cs プロジェクト: JanZeman/BugSense-WP8
        public async static Task<Tuple<string, bool>> ReadFrom(string fpathname)
        {
#if WINDOWS_PHONE
            return await Task.Run(() =>
                {
                    using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!storage.FileExists(fpathname))
                            return new Tuple<string, bool>("", false);
                        using (var fileStream = storage.OpenFile(fpathname, FileMode.Open))
                        {
                            using (StreamReader sr = new StreamReader(fileStream))
                            {
                                string data = sr.ReadToEnd();

                                return new Tuple<string, bool>(data, true);
                            }
                        }
                    }
                });
#elif NETFX_CORE
            Tuple<string, bool> result = new Tuple<string, bool>("", false);
            StorageFile file = null;

            try
            {
                file = await ApplicationData.Current.LocalFolder.GetFileAsync(fpathname);
                if (file == null)
                    return result;
            }
            catch (Exception)
            {
                return result;
            }

            using (var fs = await file.OpenAsync(FileAccessMode.Read))
            {
                using (var inStream = fs.GetInputStreamAt(0))
                {
                    using (var reader = new DataReader(inStream))
                    {
                        await reader.LoadAsync((uint)fs.Size);
                        string data = reader.ReadString((uint)fs.Size);
                        reader.DetachStream();

                        result = new Tuple<string, bool>(data, true);
                    }
                }
            }

            return result;
#else
			return await Task.Run (() => {
				try
				{
					string str = File.ReadAllText(fpathname);
					return new Tuple<string, bool>(str, true);
				}
				catch (Exception)
				{
					return new Tuple<string, bool>("", false);
				}
			});
#endif
        }
コード例 #20
0
        public override void Run()
        {
            #if WINRT
            StorageFile file = Package.Current.InstalledLocation.GetFileAsync(_path).AsTask().Result;
            using(var raStream = file.OpenReadAsync().AsTask().Result)
            {
                byte[] blob = new byte[CHUNK_SIZE];

                while (IsRunning && raStream.CanRead)
                {
                    DataReader reader = new DataReader(raStream.GetInputStreamAt(0));
                    reader.InputStreamOptions = InputStreamOptions.Partial;
                    try
                    {
                        reader.LoadAsync((uint)blob.Length).AsTask().Wait();
                        int bytesRead = 0;
                        while (reader.UnconsumedBufferLength > 0)
                        {
                            blob[bytesRead++] = reader.ReadByte();
                        }

                        if (bytesRead > 0)
                        {
                            HandleData(blob, bytesRead);
                        }
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        reader.DetachStream();
                        reader.Dispose();
                    }

                    if (raStream.Position >= raStream.Size)
                    {
                        Terminate();
                        break;
                    }

                    Task.Delay(INTERVAL).Wait();
                }
            }
            #else
            byte [] blob = new byte[CHUNK_SIZE];

            while(IsRunning && _fileStream.CanRead)
            {
                int read = _fileStream.Read(blob, 0, CHUNK_SIZE);

                if( read > 0 )
                {
                    HandleData(blob, read);
                }

                if(_fileStream.CanSeek && _fileStream.Position >= _fileStream.Length)
                {
                    Terminate();
                    break;
                }

                Thread.Sleep(INTERVAL);
            }
            #endif
        }
コード例 #21
0
        private async void OnForegroundSocketClicked(object sender, RoutedEventArgs e)
        {
            socket = new StreamSocket();
            HostName host = new HostName("localhost");

            try
            {
                await socket.ConnectAsync(host, "1983");

                isConnected = true;
                while (isConnected)
                {
                    try
                    {
                        DataReader reader;

                        using (reader = new DataReader(socket.InputStream))
                        {
                            // Set the DataReader to only wait for available data (so that we don't have to know the data size)
                            reader.InputStreamOptions = InputStreamOptions.Partial;
                            // The encoding and byte order need to match the settings of the writer we previously used.
                            reader.UnicodeEncoding = UnicodeEncoding.Utf8;
                            reader.ByteOrder = ByteOrder.LittleEndian;

                            // Send the contents of the writer to the backing stream. 
                            // Get the size of the buffer that has not been read.
                            await reader.LoadAsync(256);

                            // Keep reading until we consume the complete stream.
                            while (reader.UnconsumedBufferLength > 0)
                            {
                                string readString = reader.ReadString(reader.UnconsumedBufferLength);
                                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    messages.Add(readString);
                                });
                                Debug.WriteLine(readString);
                                await reader.LoadAsync(256);
                            }

                            reader.DetachStream();

                        }

                    }
                    catch (Exception exc)
                    {
                        MessageDialog dialog = new MessageDialog("Error reading the data");
                        await dialog.ShowAsync();
                    }
                }
            }
            catch (Exception exc)
            {
                MessageDialog dialog = new MessageDialog("Error connecting to the socket");
                await dialog.ShowAsync();
            }
        }
コード例 #22
0
ファイル: SocketClass.cs プロジェクト: Chrislaos/MetroSocket2
        async private void recieveData()
        {
            StreamSocketListener listener = new StreamSocketListener();
            DataReader dr = new DataReader(socket.InputStream);
            dr.InputStreamOptions = InputStreamOptions.Partial;
            string msg = null;
            var count = await dr.LoadAsync(8192);

            if (count > 0)
                msg = dr.ReadString(count);

            dr.DetachStream();
            dr.Dispose();

            try
            {
                pdu2 = new PDU(msg);
                ListOfProcedures temp = pdu2.Data.ToObject(typeof(ListOfProcedures));
                foreach (Procedure pro in temp.ProcedureList)
                {
                    _kakecollection.Add(pro);
                }
            }
            catch (Exception e) { recievedMessage.Text = "Failed to cast incomming message to usable type: PDU"; }
        }
コード例 #23
0
        async private void ReadButton_Click(object sender, RoutedEventArgs e)
        {
            if (EventHandlerForDevice.Current.IsDeviceConnected)
            {
                try
                {
                    rootPage.NotifyUser("Reading...", NotifyType.StatusMessage);

                    // We need to set this to true so that the buttons can be updated to disable the read button. We will not be able to
                    // update the button states until after the read completes.
                    IsReadTaskPending = true;
                    DataReaderObject = new DataReader(EventHandlerForDevice.Current.Device.InputStream);
                    UpdateReadButtonStates();

                    await ReadAsync(ReadCancellationTokenSource.Token);
                }
                catch (OperationCanceledException /*exception*/)
                {
                    NotifyReadTaskCanceled();
                }
                catch (Exception exception)
                {
                    MainPage.Current.NotifyUser(exception.Message.ToString(), NotifyType.ErrorMessage);
                    Debug.WriteLine(exception.Message.ToString());
                }
                finally
                {
                    IsReadTaskPending = false;
                    DataReaderObject.DetachStream();
                    DataReaderObject = null;

                    UpdateReadButtonStates();
                }
            }
            else
            {
                Utilities.NotifyDeviceNotConnected();
            }
        }
コード例 #24
0
        private static async Task<string> Receive(StreamSocket socket)
        {
            string result = null;

            if (socket != null)
                using (var reader = new DataReader(socket.InputStream))
                {
                    reader.InputStreamOptions = InputStreamOptions.Partial;

                    uint sizeFieldLength = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldLength == sizeof(uint))
                    {
                        uint dataLength = reader.ReadUInt32();
                        uint actualDataLength = await reader.LoadAsync(dataLength);
                        if (dataLength == actualDataLength)
                            result = reader.ReadString(actualDataLength);
                    }

                    reader.DetachStream();
                }

            return result;
        }
コード例 #25
0
        private static async Task<string> GetReceiptAsync(string productId)
        {
            var encryptedFilename = CipherEncryption(productId);
            var encodedFileName = Convert.ToBase64String(encryptedFilename.ToArray());
            var encodedAndEscapedFilename = encodedFileName.Replace('/', '-');

            //var folder = ApplicationData.Current.RoamingFolder;
            var folder = ApplicationData.Current.RoamingFolder;
            if (folder == null) return "NoReceipt";
            folder = await folder.CreateFolderAsync("Receipts", CreationCollisionOption.OpenIfExists);
            try
            {
                var file = await folder.GetFileAsync(encodedAndEscapedFilename + ".pmd");

                var stream = await file.OpenAsync(FileAccessMode.Read);
                var dataReader = new DataReader(stream.GetInputStreamAt(0));
                uint u = await dataReader.LoadAsync((uint)stream.Size);
                IBuffer buffEncrypted = dataReader.ReadBuffer(u);

                dataReader.DetachStream();
                stream.Dispose();
                stream = null;

                var receipt = CipherDecryption(buffEncrypted);

                if (productId.Contains("subscritpion") && DownloadManager.ReceiptExpired(receipt))
                {
                    await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
                    return "NoReceipt";
                }

                return receipt;
            }
            catch (Exception)
            {
                return "NoReceipt";
            }
        }
コード例 #26
0
ファイル: FtpClient.cs プロジェクト: MalakP/WinRTFtpLibrary
        /// <summary>
        /// Read the input stream of the data socket.
        /// </summary>
        /// <returns>FtpResponse containing what has been on the socket.</returns>
        private async Task<FtpFileResponse> ReadSocketFileDataReceiver()
        {
            try
            {
                DataReader inputStream = new DataReader(socketDataReceiver.InputStream);
                inputStream.InputStreamOptions = InputStreamOptions.Partial;


                DataReaderLoadOperation loadOperation = inputStream.LoadAsync(2500);
                await loadOperation;
                if (loadOperation.Status != AsyncStatus.Completed)
                {

                    return new FtpFileResponse(loadOperation.Status.ToString(), null);
                }

                //read complete message
                uint byteCount = inputStream.UnconsumedBufferLength;

                byte[] bytes = new byte[byteCount];
                inputStream.ReadBytes(bytes);

                FtpFileResponse lResponse = new FtpFileResponse(FtpConstants.CODE_TRANSFER_COMPLETE, bytes);

                //detach stream so that it won't be closed when the datareader is disposed later
                inputStream.DetachStream();
                return lResponse;
            }
            catch (Exception e)
            {
                return new FtpFileResponse(Convert.ToString(e.HResult), null);
            }
        }
コード例 #27
0
 private static async Task<byte[]> ReadBytesAsync(StorageFile file)
 {
     using (var fs = await file.OpenAsync(FileAccessMode.Read))
     {
         using (var inStream = fs.GetInputStreamAt(0))
         {
             using (var dataReader = new DataReader(inStream))
             {
                 await dataReader.LoadAsync((uint)fs.Size);
                 var data = new byte[dataReader.UnconsumedBufferLength];
                 dataReader.ReadBytes(data);
                 dataReader.DetachStream();
                 return data;
             }
         }
     }
 }
コード例 #28
0
        public async Task LoadCookiesAsync(Guid requestId)
        {
            string data = null;
            var cookieContainer = new CookieContainer();

            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(CookieCacheFile, CreationCollisionOption.OpenIfExists);
            using (var fs = await file.OpenAsync(FileAccessMode.Read))
            {
                using (var inStream = fs.GetInputStreamAt(0))
                {
                    using (var dataReader = new DataReader(inStream))
                    {
                        await dataReader.LoadAsync((uint)fs.Size);
                        data = dataReader.ReadString((uint)fs.Size);
                        dataReader.DetachStream();

                        var cookies = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Cookie>>>(data);
                        if (cookies != null)
                        {
                            foreach (var cookieSet in cookies)
                            {
                                foreach (var cookie in cookieSet.Value)
                                {
                                    cookieContainer.Add(new Uri(cookie.Key), cookie.Value);
                                }
                            }
                        }

                        this.knownCookies = cookieContainer;
                        this.persistentCookies = cookies ?? new Dictionary<string, Dictionary<string, Cookie>>();
                    }
                }
            }

            Trace.Verbose(requestId, "Loaded {0} cookies: {1}\r\n", cookieContainer.Count, data);
        }
コード例 #29
0
ファイル: Networking.cs プロジェクト: nidzo732/FileTransfer
 public async Task<string> Recv()
 {
     string headerBuffer = "";
     try
     {
         DataReader socketDataReader = new DataReader(internalSocket.InputStream);
         while (!headerBuffer.EndsWith("MLEN") && headerBuffer.Length < MAX_HEADER_LENGTH)
         {
             await socketDataReader.LoadAsync(1).AsTask(getTimeoutToken());
             headerBuffer += socketDataReader.ReadString(1);
         }
         if (!headerBuffer.EndsWith("MLEN"))
         {
             return null;
         }
         UInt64 length;
         if (!UInt64.TryParse(headerBuffer.Replace("MLEN", ""), out length))
         {
             return null;
         }
         byte[] data = new byte[length];
         ulong dataReceived = 0;
         while (dataReceived < length)
         {
             int currentChunkSize = CHUNK_SIZE;
             if (length - dataReceived < CHUNK_SIZE) currentChunkSize = (int)(length - dataReceived);
             byte[] chunk = new byte[currentChunkSize];
             await socketDataReader.LoadAsync((uint)currentChunkSize).AsTask(getTimeoutToken());
             socketDataReader.ReadBytes(chunk);
             Array.Copy(chunk, 0, data, (int)dataReceived, currentChunkSize);
             dataReceived += (ulong)currentChunkSize;
             repportProgress((int)dataReceived, (int)length);
         }
         socketDataReader.DetachStream();
         return Cryptography.TextManipulation.DecodeUTF(data);
     }
     catch (Exception error)
     {
         throw new NetworkingError(error.Message);
     }
 }
コード例 #30
0
ファイル: Publisher.cs プロジェクト: CHS982/Coding4Fun
        public async void Send(byte[] fileBytes)
        {
            try
            {
                if (Speakers != null && Speakers.Count > 0 && fileBytes != null)
                {
                    //iterate through the speakers and send out the media file to each speaker
                    foreach (Speaker speaker in Speakers)
                    {
                        StreamSocket socket = speaker.Socket;

                        if (socket != null)
                        {
                            IOutputStream outStream = socket.OutputStream;
                            using (DataWriter dataWriter = new DataWriter(outStream))
                            {
                                //write header bytes to indicate to the subscriber 
                                //information about the file to be sent
                                dataWriter.WriteInt16((short)MessageType.Media);
                                dataWriter.WriteInt32(fileBytes.Length);
                                await dataWriter.StoreAsync();
                                //start from 0 and increase by packet size
                                int partNumber = 0;
                                int sourceIndex = 0;
                                int bytesToWrite = fileBytes.Length;
                                while (bytesToWrite > 0)
                                {
                                    dataWriter.WriteInt32(partNumber);
                                    int packetSize = bytesToWrite;
                                    if (packetSize > MAX_PACKET_SIZE)
                                    {
                                        packetSize = MAX_PACKET_SIZE;
                                    }
                                    byte[] fragmentedPixels = new byte[packetSize];
                                    Array.Copy(fileBytes, sourceIndex, fragmentedPixels, 0, packetSize);
                                    dataWriter.WriteBytes(fragmentedPixels);
                                    Debug.WriteLine("sent byte packet length " + packetSize);
                                    await dataWriter.StoreAsync();
                                    sourceIndex += packetSize;
                                    bytesToWrite -= packetSize;
                                    partNumber++;
                                    Debug.WriteLine("sent total bytes " + (fileBytes.Length - bytesToWrite));
                                }
                                //Finally DetachStream
                                dataWriter.DetachStream();
                            }
                        }
                    }


                    //check the speakers have all received the file
                    foreach (Speaker speaker in Speakers)
                    {
                        StreamSocket socket = speaker.Socket;
                        if (socket != null)
                        {
                            //wait for the 'I got it' message
                            DataReader reader = new DataReader(socket.InputStream);
                            uint x = await reader.LoadAsync(sizeof(short));
                            MessageType t = (MessageType)reader.ReadInt16();
                            if (MessageType.Ready == t)
                            {
                                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                () =>
                                {
                                    Speakers.Remove(speaker);
                                    speaker.Status = "Ready";
                                    Speakers.Add(speaker);
                                });
                            }
                            reader.DetachStream();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
コード例 #31
0
        private async Task<string> Receive()
        {
            if (socket == null) return null;
            

            using (DataReader reader = new DataReader(socket.InputStream))
            {
                

              //  reader.InputStreamOptions = InputStreamOptions.Partial;
                reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                reader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                
                   

                    try
                    {
                    while (true)
                    {
                        StringBuilder ImageStrBuilder = new StringBuilder();
                        // Set the DataReader to only wait for available data (so that we don't have to know the data size)
                        // reader.InputStreamOptions = Windows.Storage.Streams.InputStreamOptions.Partial;
                        // The encoding and byte order need to match the settings of the writer we previously used.


                        // Send the contents of the writer to the backing stream. 
                        // Get the size of the buffer that has not been read.

                        // await  Task.Delay(50);
                        //  if (socket == null) return null;


                        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 null;
                        }



                        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 null;
                        }

                        // Keep reading until we consume the complete stream.
                        // while (reader.UnconsumedBufferLength > 0)
                        //     {
                        //        ImageStrBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
                        //        await reader.LoadAsync(2048);

                        //    }



                        //    ImageString = ImageStrBuilder.ToString();


                        //    else if (ImageStrBuilder.Length < 100 && ImageStrBuilder.Length > 0)
                        //    {
                        //         Calculate(ImageString);
                        //     }





                        // ClientAddLine("Received(" + DateTime.Now.ToString("h:mm:ss") + "): " + ImageStrBuilder.ToString());
                        //await Task.Factory.StartNew(ReloadPicture);
                        // Send(2);
                        ImageStrBuilder.Append(reader.ReadString(actualStringLength));

                        // reader.DetachBuffer();
                         reader.DetachStream();
                        // reader.Dispose();

                        return ImageStrBuilder.ToString();
                        //  return "error";


                    }


                    }
                    catch (Exception e)
                    {
                    //   ClientWaitForMessage();
                    //received = false;
                    return "error";
                    }




                
            }


        }
コード例 #32
0
ファイル: Publisher.cs プロジェクト: CHS982/Coding4Fun
        private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.WriteLine("Connection Received on Port {0}", sender.Information.LocalPort);
            StreamSocket streamSocket = args.Socket;
            if (streamSocket != null)
            {
                DataReader reader = new DataReader(streamSocket.InputStream);
                try
                {
                    // 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 length of the 'packet'.
                    uint length = reader.ReadUInt32();
                    uint actualLength = await reader.LoadAsync(length);
                    if (length != actualLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    string name = reader.ReadString(actualLength);
                    Speaker speaker = new Speaker()
                    {
                        Name = name,
                        Address = streamSocket.Information.RemoteAddress.DisplayName,
                        Status = "Connected",
                        Socket = streamSocket
                    };

                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                    () =>
                    {
                        Speakers.Add(speaker);
                    });

                    reader.DetachStream();

                    Debug.WriteLine("New speaker added " + name);

                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error in connection received: " + e);
                }
            }
        }
コード例 #33
0
        /// <summary>
        /// Invoked when the socket listener accepted an incoming Bluetooth connection.
        /// </summary>
        /// <param name="sender">The socket listener that accecpted the connection.</param>
        /// <param name="args">The connection accept parameters, which contain the connected socket.</param>
        private async void OnConnectionReceived(
            StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                NotifyStatus("Client Connected");

                // Don't need the listener anymore
                socketListener.Dispose();
                socketListener = null;

                socket = args.Socket;

                writer = new DataWriter(socket.OutputStream);

                var reader = new DataReader(socket.InputStream);
                bool remoteDisconnection = false;
                while (true)
                {
                    uint readLength = await reader.LoadAsync(sizeof(uint));
                    if (readLength < sizeof(uint))
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    uint currentLength = reader.ReadUInt32();

                    readLength = await reader.LoadAsync(currentLength);
                    if (readLength < currentLength)
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    string message = reader.ReadString(currentLength);

                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        ConversationListBox.Items.Add("Received: " + message);
                    });
                }

                reader.DetachStream();
                if (remoteDisconnection)
                {
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Disconnect();
                        NotifyStatus("Client disconnected.");
                    });
                }
            }
            catch (Exception e)
            {
                NotifyError(e);
            }
        }
コード例 #34
0
        private async Task<UInt32> serialReadAsync(uint read_size)
        {
            try
            {
                if (serialPort == null)
                {
                    printLog("No port selected");
                    return 0;
                }
                //TODO handle cancelationTokens
                using (DataReader dataReaderObject = new DataReader(serialPort.InputStream))
                {

                    // Launch the task and wait
                    UInt32 bytesRead = await dataReaderObject.LoadAsync(read_size);

                    for (int i = 0; i < bytesRead; i++)
                    {
                        serialReceive[i] = dataReaderObject.ReadByte();
                    }
                    dataReaderObject.DetachStream();
                    return bytesRead;
                }
            }
            catch (Exception ex)
            {
                printLog(ex.Message);
                return 0;
            }
        }