ReadLineAsync() public method

public ReadLineAsync ( ) : Task
return Task
Example #1
0
        public async Task ResponseLimit()
        {
            var client = CreateClient();
            var url = BaseUrl + "/000/" + Guid.NewGuid().ToString();

            var request = new HttpRequestMessage(HttpMethod.Post, url + "/xhr_streaming");
            var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

            string msg = "\"" + new string('x', 128) + "\"";
            int nrOfMessages = 31;
            for (int i = 0; i < nrOfMessages; i++)
            {
                var sendResponse = await client.PostAsync(url + "/xhr_send", new StringContent("[" + msg + "]", Encoding.UTF8, "application/json"));
                Assert.Equal(HttpStatusCode.NoContent, sendResponse.StatusCode);
            }

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var contentStream = await response.Content.ReadAsStreamAsync();
            var reader = new StreamReader(contentStream);
            var prelude = await reader.ReadLineAsync();
            var open = await reader.ReadLineAsync();
            Assert.Equal(new string('h', 2048), prelude);
            Assert.Equal("o", open);
            var remaining = await reader.ReadToEndAsync();
            Assert.Equal(string.Concat(Enumerable.Repeat("a[" + msg + "]\n", nrOfMessages)), remaining);
        }
 public static async void InitLoadSet() {
   string fileContent;
   Uri uri = new Uri("ms-appx:///Data/Sets.txt");
   file = await StorageFile.GetFileFromApplicationUriAsync(uri);
   StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync());
   fileContent = await sRead.ReadLineAsync();
   KeyValuePair<int, object> res = Type(fileContent);
   ListWords currentListWords = new ListWords();
   while (res.Key != -1)
   {
     if (res.Key == 0)
     {
       currentListWords.Name = (string)res.Value;
       SetsNames.Add((string)res.Value);
     }
     if (res.Key == 1)
     {
       currentListWords.Add((Word)res.Value);
     }
     if (res.Key == 2)
     {
       SetsWords.Add(currentListWords.Name, currentListWords);
       currentListWords = new ListWords();
     }
     fileContent = sRead.ReadLineAsync().Result;
     res = Type(fileContent);
   }
   MainPage.CurrentListWords = SetsWords["None"];
   sRead.Dispose();
 }
 private async void Open_Stream_Click(object sender, RoutedEventArgs e)
 {
     (sender as Button).IsEnabled = false;
     string url = String.Format("https://api.particle.io/v1/devices/{0}/events/NeedCover?access_token={1}", PHOTON1DEVICEID, ACCESS_TOKEN);
     WebRequest request = WebRequest.Create(url);
     request.Method = "GET";
     using (WebResponse response = await request.GetResponseAsync())
     {
         using (Stream stream = response.GetResponseStream())
         {
             StreamReader reader = new StreamReader(stream);
             int blankRead = 0;
             while (blankRead <= 1)
             {
                 // Event comes streaming in 3 lines. blank line, 
                 // "event: NeedCover", 
                 // then a json line that starts with "data:",
                 // If more than a couple blank lines in a row then we're done with the stream.
                 var str = await reader.ReadLineAsync();
                 if (string.IsNullOrEmpty(str))
                 {
                     ++blankRead;
                 }
                 else if (str == "event: NeedCover")
                 {
                     blankRead = 0;
                     var data = await reader.ReadLineAsync();
                     var jsonData = JsonConvert.DeserializeObject<ParticleEvent>(data.Substring(data.IndexOf("data:") + 5));
                     streamResultTextBox.Text = jsonData.data;
                 }
             }
         }
     }
     (sender as Button).IsEnabled = true;
 }
Example #4
0
        public async Task Transport()
        {
            var client = CreateClient();
            var url = BaseUrl + "/000/" + Guid.NewGuid().ToString();

            var request = new HttpRequestMessage(HttpMethod.Post, url + "/xhr_streaming");
            var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("UTF-8", response.Content.Headers.ContentType.CharSet);
            Assert.Equal("application/javascript", response.Content.Headers.ContentType.MediaType);
            AssertCors(response, null);

            var contentStream = await response.Content.ReadAsStreamAsync();
            var reader = new StreamReader(contentStream);
            var prelude = await reader.ReadLineAsync();
            var open = await reader.ReadLineAsync();
            Assert.Equal(new string('h', 2048), prelude);
            Assert.Equal("o", open);

            var sendResponse = await client.PostAsync(url + "/xhr_send", new StringContent("[\"x\"]", Encoding.UTF8, "application/json"));
            Assert.Equal(HttpStatusCode.NoContent, sendResponse.StatusCode);

            var message = await reader.ReadLineAsync();
            Assert.Equal("a[\"x\"]", message);

            client.Dispose();
        }
Example #5
0
        private async void ClientWork(object state)
        {
            int clientId = (int)state;
            using (var channel = this.connection.ConnectChannel())
            {
                using (StreamWriter writer = new StreamWriter(channel))
                {
                    using (StreamReader reader = new StreamReader(channel))
                    {
                        string request = string.Format("Hello from {0}", clientId);
                        string response;
                        await writer.WriteLineAsync(request);
                        await writer.FlushAsync();
                        response = await reader.ReadLineAsync();
                        await writer.WriteLineAsync(request);
                        await writer.FlushAsync();
                        response = await reader.ReadLineAsync();
                        await channel.StopSendingAsync();
                        await channel.FlushAsync();
                        if (reader.EndOfStream)
                        {
                            Console.WriteLine("Client feel right!");
                        }
                    }
                }
            }

            if (Interlocked.Decrement(ref pendingCount) == 0)
            {
                lock (termLock)
                {
                    Monitor.Pulse(termLock);
                }
            }
        }
Example #6
0
        private static async Task WorkAsync(Channel channel)
        {
            using (channel)
            {
                using (var reader = new StreamReader(channel))
                {
                    using (var writer = new StreamWriter(channel))
                    {
                        string request = await reader.ReadLineAsync();
                        await writer.WriteLineAsync(request);
                        await writer.FlushAsync();

                        request = await reader.ReadLineAsync();
                        await writer.WriteLineAsync(request);
                        await writer.FlushAsync();

                        Console.WriteLine("Server waiting for close");

                        if (reader.EndOfStream)
                        {
                            Console.WriteLine("Server feel right!");
                        }

                        await channel.StopSendingAsync();
                        await channel.FlushAsync();
                    }
                }
            }
        }
        public async Task<bool> HandshakeConnection(NetworkStream ClientStream)
        {
            StreamReader Reader = new StreamReader(ClientStream);
            StreamWriter Writer = new StreamWriter(ClientStream);

            TCPGetRequestHeader RequestHeader = new TCPGetRequestHeader();

            string message = await Reader.ReadLineAsync();
            while (message != Terminal)
            {
                this.ParseHeader(message, ref RequestHeader);
                message = await Reader.ReadLineAsync();
            }

            string accept = this.AcceptKey(RequestHeader.SocketKey);

            Writer.Write("HTTP/1.1 101 Switching Protocols\r\n");
            Writer.Write("Upgrade: websocket\r\n");
            Writer.Write("Connection: Upgrade\r\n");
            Writer.Write("Sec-WebSocket-Accept: " + accept + "\r\n");
            Writer.Write("\r\n");

            Writer.Flush();

            return true;
        }
Example #8
0
        private async void MainForm_Load(object sender, EventArgs e)
        {
            #region 进度提示窗口设置
            ProgressForm progressForm = new ProgressForm();
            progressForm.Size = new Size(600, 80);
            progressForm.StartPosition = FormStartPosition.Manual;
            progressForm.Location = new Point(this.DesktopLocation.X + this.Width / 2 - progressForm.Size.Width / 2, this.DesktopLocation.Y + this.Height / 2 - progressForm.Size.Height / 2);
            progressForm.FormBorderStyle = FormBorderStyle.FixedToolWindow;
            progressForm.progress.Maximum = 100;
            progressForm.progress.Minimum = 0;
            progressForm.progress.Value = 0;
            progressForm.Show(this);
            this.Enabled = false;
            #endregion

            using (StreamReader reader = new StreamReader("TitleUrl.txt"))
            {
                while (!reader.EndOfStream)
                {
                    string title = await reader.ReadLineAsync();
                    string url = await reader.ReadLineAsync();

                    try
                    {
                        titleURL.Add(title, url);
                    }
                    catch (Exception)
                    {
                        // 异常:
                        //   T:System.ArgumentNullException:
                        //     key 为 null。
                        //
                        //   T:System.ArgumentException:
                        //     System.Collections.Generic.Dictionary`2 中已存在具有相同键的元素。
                    }

                    //更新进度条
                    if (progressForm.progress.Value < 90)
                    {
                        progressForm.progress.Value++;
                        progressForm.Text = "正在加载离线数据:" + progressForm.progress.Value + "%";                        
                    }

                }
            }

            progressForm.progress.Value = 100;
            progressForm.Text = "任务进度:" + progressForm.progress.Value + "%";
            progressForm.Close();
            this.Enabled = true;

        }
        /// <summary>
        /// Splits the file into the specified number of files.
        /// </summary>
        /// <param name="filePath">The file to split.</param>
        /// <param name="fileCount">The number of files to split the original file into.</param>
        /// <returns>The list of file names generated by splitting the original file.</returns>
        public async Task<List<string>> SplitAsync(string filePath, int fileCount)
        {
            List<string> filePaths = new List<string>();

            //Load the existing file.
            using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
            {
                using (StreamReader streamReader = new StreamReader(fileStream))
                {
                    //Count the total number of lines in the original file.
                    int lineCount = 0;
                    while (!streamReader.EndOfStream)
                    {
                        ++lineCount;
                        await streamReader.ReadLineAsync();
                    }

                    //Compute the number of lines per file.
                    int linesPerFile = lineCount / fileCount;

                    streamReader.BaseStream.Seek(0, SeekOrigin.Begin);

                    //Generate each output file.
                    for(int i = 0; i < fileCount; i++)
                    {
                        string fileName = Helpers.GetSplitFileName(i);
                        
                        filePaths.Add(fileName);

                        using (FileStream newFileStream = new FileStream(fileName, FileMode.Create))
                        {
                            using (StreamWriter streamWriter = new StreamWriter(newFileStream))
                            {
                                for (int linesInCurrentFile = 0; 
                                    linesInCurrentFile < linesPerFile ||
                                    (i == fileCount - 1 && !streamReader.EndOfStream); //Write any remaining lines (due to rounding) to the last file.
                                    linesInCurrentFile++)
                                {
                                    string line = await streamReader.ReadLineAsync();

                                    await streamWriter.WriteLineAsync(line);
                                }
                            }
                        }
                    }

                }
            }

            return filePaths;
        }
        private async void ServerStub(TcpClient client)
        {
            string ipClient = client.Client.RemoteEndPoint.ToString();
            Console.WriteLine("Подключился клиент: {0}", ipClient);

            NetworkStream ns = client.GetStream();
            StreamWriter sw = new StreamWriter(ns);
            StreamReader sr = new StreamReader(ns);

            try
            {
                string method = await sr.ReadLineAsync();
                int arg1 = int.Parse(await sr.ReadLineAsync());
                int arg2 = int.Parse(await sr.ReadLineAsync());
                int res = 0;

                switch (method)
                {
                    case "+":
                        res = add(arg1, arg2);
                        break;

                    case "-":
                        res = sub(arg1, arg2);
                        break;

                    case "*":
                        res = mul(arg1, arg2);
                        break;

                    default:
                        throw new Exception("Неверный код функции");
                }

                sw.WriteLine(res);

                Console.WriteLine("Клиент {0} присал сообщение: {1} {2} {3} | {4}", ipClient, method, arg1, arg2, res);
            }
            catch (Exception e)
            {
                Console.WriteLine("Ошибка при обработке пакета от клиента: {0}", ipClient);
                System.Diagnostics.Debug.WriteLine(e.StackTrace);
            }
            finally
            {
                sw.Close();
                sr.Close();
                client.Close();
                Console.WriteLine("Клиент отключился: {0}", ipClient);
            }
        }
Example #11
0
        protected override async Task HandleClient(TcpClient client) {
            using (var stream = client.GetStream())
            using (var reader = new StreamReader(stream))
            using (var writer = new StreamWriter(stream)) {

                string line = await reader.ReadLineAsync().ConfigureAwait(false);

                while (line != null) {
                    writer.WriteLine(line);
                    writer.Flush();
                    line = await reader.ReadLineAsync().ConfigureAwait(false);
                }
            }
        }
Example #12
0
        /// <summary>
        /// Runs the mapper task.
        /// </summary>
        public async Task RunAsync()
        {
            CloudBlockBlob blob = new CloudBlockBlob(new Uri(this.blobSas));
            Console.WriteLine("Matches in blob: {0}/{1}", blob.Container.Name, blob.Name);

            using (Stream memoryStream = new MemoryStream())
            {
                //Download the blob.
                await blob.DownloadToStreamAsync(memoryStream);
                memoryStream.Seek(0, SeekOrigin.Begin);

                using (StreamReader streamReader = new StreamReader(memoryStream))
                {
                    Regex regex = new Regex(this.configurationSettings.RegularExpression);

                    int lineCount = 0;

                    //Read the file content.
                    while (!streamReader.EndOfStream)
                    {
                        ++lineCount;
                        string textLine = await streamReader.ReadLineAsync();

                        //If the line matches the search parameters, then print it out.
                        if (textLine.Length > 0)
                        {
                            if (regex.Match(textLine).Success)
                            {
                                Console.WriteLine("Match: \"{0}\" -- line: {1}", textLine, lineCount);
                            }
                        }
                    }
                }
            }
        }
        public async Task TestTcpTraceListener()
        {
            var listener = new TcpListener(IPAddress.Loopback, 0);
            listener.Start();
            int port = ((IPEndPoint)listener.Server.LocalEndPoint).Port;


            var traceSource = new TraceSource("UnitTestLogger");
            traceSource.Listeners.Remove("Default");
            traceSource.Switch.Level = SourceLevels.All;
            traceSource.Listeners.Add(new TcpTraceListener(
                                            IPAddress.Loopback, port, 
                                            new ExponentialBackoffTcpReconnectionPolicy()));

            var listenerClient = await listener.AcceptTcpClientAsync();

            traceSource.TraceEvent(TraceEventType.Information, 100, "Boris");

            var receiverReader = new StreamReader(listenerClient.GetStream());
            var line = await receiverReader.ReadLineAsync();

            Assert.True(line.EndsWith("UnitTestLogger Information: 100 : Boris"));

            listenerClient.Close();
            listener.Stop();
            traceSource.Close();
        }
Example #14
0
 public static async Task ProcessStream(Stream networkStream)
 {
     try
     {
         StreamReader reader = new StreamReader(networkStream);
         StreamWriter writer = new StreamWriter(networkStream);                   
         writer.AutoFlush = true;
         while (true)
         {
             string request = await reader.ReadLineAsync();
             if (request != null)
             {
                 Console.WriteLine("Received echo: " + request);
                 string echo_str = await CommandResolve.Resolve(request);
                 if (!String.IsNullOrEmpty(echo_str))
                 {
                     await writer.WriteLineAsync(echo_str);
                 }
                 else
                     break; // unvalid command or command complete
             }
             else
                 break; // Client closed connection
         }                                   
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Example #15
0
        public async Task<string[]> ReadAllLinesAsync(string path, Encoding encoding)
        {
            System.Diagnostics.Debug.WriteLine("Reading");
            var lines = new List<string>();
            char[] delimiterChars = { ',', ':', '\t' };

            using (var reader = new StreamReader(path, encoding))
            {
                string line;
                while ((line = await reader.ReadLineAsync()) != null)
                {
                    lines.Add(line);
                }
            }
            //Adds items to database based on the words in each line of the file.
            foreach (string item in lines)
            {
                string[] words = item.Split(delimiterChars);
                System.Diagnostics.Debug.WriteLine("Hello from the other side");
                DateTime date = new DateTime(2016, 6, 11);
                if (NewItem(Convert.ToInt32(words[0]), words[1], words[2], words[3], float.Parse(words[4]), Convert.ToInt32(words[5]), Convert.ToInt32(words[6]), Convert.ToInt32(words[7]), date))

                {
                    Console.WriteLine("Success");
                }
                else
                {
                    Console.WriteLine("Fail");
                }

            }
            //Deletes the file when done reading.
            File.Delete(path);
            return lines.ToArray();
        }
        async void ReceiveData(TcpClient client)
        {
            NetworkStream stream = client.GetStream();
            StreamReader reader = new StreamReader(stream);

            while (true)
            {
                string message = await reader.ReadLineAsync();

                // If message is null then the client has disconnected
                if(message == null)
                {
                    clients.Remove(client);

                    Trace.TraceInformation("Disconnected from client {0}", client.Client.RemoteEndPoint.ToString());

                    return;
                }

                Trace.TraceInformation("Received data from client {0}: {1}", client.Client.RemoteEndPoint.ToString(), message);

                // Process data
                string[] words = message.Split(' ');
                if(words[0] == "GameResults")
                {
                    Game.RoundResults.Add(client.Client.RemoteEndPoint.ToString(), int.Parse(words[1]));
                }
            }
        }
Example #17
0
        private static async Task<bool> ParseHeadingLineAsync(StreamReader reader,
            Action<string, string, string> onHeadingLine)
        {
            var line = await reader.ReadLineAsync();

            return RawParser.ParseHeadingLine(line, onHeadingLine);
        }
        public async Task HandleClientAsync(TcpClient c)
        {
            string msg = null;
            bool connected = true;

            Console.WriteLine($"Connection accepted {DateTime.Now.ToShortTimeString()}");
            using (var output = new StreamWriter(c.GetStream(), UTF32Encoding.ASCII) { AutoFlush = true })
            {
                using (var input = new StreamReader(c.GetStream(), UTF32Encoding.ASCII))
                {
                    while (connected)
                    {
                        switch (msg = await input.ReadLineAsync())
                        {
                            case "done":
                                connected = false;
                                break;
                            default:
                                await output.WriteLineAsync(msg);
                                break;
                        }
                    }
                }

            }
            c.Close();
            Console.WriteLine("bye...");
        }
Example #19
0
        public async Task<IEnumerable<string>> LoadAsync()
        {
            List<string> feeds = new List<string>();

            try
            {
                using (FileStream fsAsync = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true))
                using (StreamReader sr = new StreamReader(fsAsync))
                {
                    string line = string.Empty;

                    while ((line = await sr.ReadLineAsync()) != null)
                    {
                        if (line.StartsWith("#") == false)
                        {
                            Uri tmp = null;
                            if (Uri.TryCreate(line, UriKind.Absolute, out tmp))
                            {
                                feeds.Add(line);
                            }
                        }
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                Utils.LogException(e);
            }

            return feeds;
        }
        public override async void GetRemoteMessage(TcpClient client)
        {
            string ipClient = client.Client.RemoteEndPoint.ToString();
            Console.WriteLine("Подключился клиент: {0}", ipClient);

            NetworkStream ns = client.GetStream();
            StreamWriter sw = new StreamWriter(ns);
            StreamReader sr = new StreamReader(ns);

            try
            {
                string message = "";
                while (message != "end")
                {
                    message = await sr.ReadLineAsync();
                    Console.WriteLine("Клиент {0} присал сообщение: {1}", ipClient, message);
                }
            }
            catch(Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
            finally
            {
                sw.Close();
                sr.Close();
                client.Close();
                Console.WriteLine("Клиент отключился: {0}", ipClient);
            }
        }
Example #21
0
 public Capitals()
 {
     foreach (var item in _fileNames)
     {
         using (StreamReader reader = new StreamReader(item, Encoding.GetEncoding("windows-1251")))
         {
             while (reader.Peek() > -1)
             {
                 Task<string> readText = reader.ReadLineAsync();
                 if (readText != null)
                 {
                     string[] cuntryAndCapital = readText.Result.Split(';');
                     cuntryAndCapital[0] = cuntryAndCapital[0].Trim();
                     cuntryAndCapital[1] = cuntryAndCapital[1].Trim();
                     Capital newOne = new Capital
                     {
                         NameCountry = cuntryAndCapital[0],
                         NameCapital = cuntryAndCapital[1]
                     };
                     _countriesWithCapitals.Add(newOne);
                 }
             }
         }
     }
 }
        private async Task MainAsync()
        {
            var connStr = "mongodb://localhost:27017";
            var client = new MongoClient(connStr);
            var db = client.GetDatabase("test");
            var col = db.GetCollection<ZipEntry>("zips");
            await db.DropCollectionAsync("zips");

            string assignmentDir = @"handouts\homework_5_2";
            string inputFileName = "small_zips.json";
            string inputFilePath = Path.Combine(assignmentDir, inputFileName);

            using (var streamReader = new StreamReader(inputFilePath))
            {
                string line;
                while ((line = await streamReader.ReadLineAsync()) != null)
                {
                    var document = BsonSerializer.Deserialize<ZipEntry>(line);
                    await col.InsertOneAsync(document);
                }
            }

            var agg = col.Aggregate()
                .Match(x => new[] { "CA", "NY" }.Contains(x.State))
                .Group(x => x.City, g => new { Count = g.Count(), TotalPop = g.Sum(x => x.Population) })
                .Match(x => x.TotalPop > 25 * 1000)
                .Group(x => true, g => new { AvgPop = g.Average(x => x.TotalPop) })
                ;

            var cmd = String.Format("db.zips.{0}", agg.ToString());
            var results = await agg.ToListAsync();
        }
        /// <summary>
        /// read data for week 3 task
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static async Task<List<Vertex>> ReadVertexArray(string fileName)
        {
            try
            {
                List<Vertex> vertices = new List<Vertex>();

                using (var stream = new StreamReader(fileName))
                {
                    while (!stream.EndOfStream)
                    {
                        var line = await stream.ReadLineAsync();
                        var values = line.Split(new char[] { '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);

                        int n = Int32.Parse(values[0]);
                        List<int> edges = new List<int>();

                        for (int i = 1; i < values.Length; i++)
                        {
                            edges.Add(Int32.Parse(values[i]));
                        }

                        vertices.Add(new Vertex(n, edges));
                    }
                }

                return vertices;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
Example #24
0
        public async Task ReceiveInput()
        {
            IsActive = true;
            _networkStream = _socket.GetStream();

            using (var reader = new StreamReader(_networkStream))
            {
                while (IsActive)
                {
                    try
                    {
                        var content = await reader.ReadLineAsync();

                        // If content is null, that means the connection has been gracefully disconnected
                        if (content == null)
                        {
                            MarkAsDisconnected();
                            return;
                        }

                        if (MessageReceived != null)
                            MessageReceived(this, content);
                    }

                    // If the tcp connection is ungracefully disconnected, it will throw an exception
                    catch (IOException)
                    {
                        MarkAsDisconnected();
                        return;
                    }
                }
            }
        }
        private async void UploadData(string collectionName, string jsonFilePath)
        {
            try
            {
                await db.DropCollectionAsync(collectionName);
                var collection = db.GetCollection<Restaurant>(collectionName);
                using (var streamReader = new StreamReader(jsonFilePath))
                {
                    string line;
                    while ((line = await streamReader.ReadLineAsync()) != null)
                    {
                        using (var jsonReader = new JsonReader(line))
                        {
                            var context = BsonDeserializationContext.CreateRoot(jsonReader);
                            var document = collection.DocumentSerializer.Deserialize(context);
                            collection.InsertOneAsync(document);
                        }
                    }
                }

                Console.WriteLine("Successfully Uploaded Grades");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception \n\n");
                Console.WriteLine(ex.Message);
            }

        }
        public async Task StartWaiting()
        {
            //SendHello
            var helloMessage = JsonConvert.SerializeObject(new MJsonMessageHello());
            SendMessageToClient(helloMessage);

            Debug.WriteLine(
                "Connect to Client ({0}:{1})" ,
                ( (IPEndPoint)tcpClient.Client.RemoteEndPoint ).Address ,
                ( (IPEndPoint)tcpClient.Client.RemoteEndPoint ).Port
                );

            try
            {
                NetworkStream stream = tcpClient.GetStream();
                StreamReader reader = new StreamReader(stream);

                while (tcpClient.Connected)
                {
                    string line = await reader.ReadLineAsync() + NetworkConstants.NewLineString;
                    //Debug.WriteLine("get:"+ line);
                    GetMessageFromClient(line);
                }
            }
            catch (IOException e)
            {
                Debug.Fail("error! : "+ e.Message);
                Disconnect();
                ClientConnectionBrokenHandler(this);
            }

        }
        public static async Task SendAndReceive()
        {
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(host, port);
                using (NetworkStream stream = client.GetStream())
                using (var writer = new StreamWriter(stream, Encoding.ASCII, 1024, leaveOpen: true))
                using (var reader = new StreamReader(stream, Encoding.ASCII, true, 1024, leaveOpen: true))
                {
                    writer.AutoFlush = true;
                    string line = string.Empty;
                    do
                    {
                        WriteLine("enter a string, bye to exit");
                        line = ReadLine();
                        await writer.WriteLineAsync(line);
                       
                        string result = await reader.ReadLineAsync();
                        WriteLine($"received {result} from server");
                    } while (line != "bye");

                    WriteLine("so long, and thanks for all the fish");

                }
            }
            
        }
        public async Task<IEnumerable<FtpFileInfo>> GetFilesListAsync(string path)
        {
            var ftpRequest = PrepareRequest(path, WebRequestMethods.Ftp.ListDirectoryDetails);

            var result = new List<FtpFileInfo>();

            using (var responce = await ftpRequest.GetResponseAsync())
            using (var stream = responce.GetResponseStream())
            {
                if (stream == null)
                {
                    throw new FtpException();
                }

                using (var streamReader = new StreamReader(stream))
                {
                    var uri = new Uri(_baseUri, path);
                    while (streamReader.EndOfStream == false)
                    {
                        var nextLine = await streamReader.ReadLineAsync();
                        var fileInfo = FtpFileInfo.Parse(nextLine);
                        fileInfo.Uri = new Uri(uri, fileInfo.Name);
                        result.Add(fileInfo);
                    }
                }
            }
            return result;
        }
Example #29
0
        /* Loaders */

        // Load specified file (if exists).
        public async void LoadFile(String file)
        {
            try
            {
                using (StreamReader reader = new StreamReader(Path.GetFullPath(file)))
                {
                    // Read single line
                    String line;
                    while ((line = await reader.ReadLineAsync()) != null)
                    {
                        // Save raw line (could be useful)
                        rawItems.Add(line);

                        // Parse line by tabs
                        List<String> subitems = line.Split('\t').ToList();
                        parsedItems.Add(subitems);
                    }

                }
            }
            catch (Exception e)
            {
                logger.Error("Could not read file {0}: {1}", file, e.Message);
            }
        }
        private async Task ParseGroundTruthTxt(string path)
        {
            _groundTruthBoxs.Clear();
            using (StreamReader reader = new StreamReader(path))
            {
                while (!reader.EndOfStream)
                {
                    string line = await reader.ReadLineAsync();
                    
                    string[] points = line.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries);

                    GroundTruthBox groundTruthBox = new GroundTruthBox();
                    
                    groundTruthBox.DownLeft.X = double.Parse(points[0]);
                    groundTruthBox.DownLeft.Y = double.Parse(points[1]);
                    groundTruthBox.DownRight.X = double.Parse(points[2]);
                    groundTruthBox.DownRight.Y = double.Parse(points[3]);
                    groundTruthBox.UpRight.X = double.Parse(points[4]);
                    groundTruthBox.UpRight.Y = double.Parse(points[5]);
                    groundTruthBox.UpLeft.X = double.Parse(points[6]);
                    groundTruthBox.UpLeft.Y = double.Parse(points[7]);

                    _groundTruthBoxs.Add(groundTruthBox);
                }
            }
        }