Data entry through C#



  • People, please tell me why my data are in the same line, not moving to a new line, and the gap is gone.

    0: 28.06.2016 22:42:511: 28.06.2016 22:42:522: 28.06.2016 22:42:533: 28.06.2016 22:42:544: 28.06.2016 22:42:55

    It has to be that:

    0: 28.06.2016 22:42:51

    1: 28.06.2016 22:42:52

    2: 28.06.2016 22:42:53

    3: 28.06.2016 22:42:54

    4: 28.06.2016 22:42:55

    The point is, the client gets these data on the earring, the variable message... the server records them in the file, and then there's a census in a minute. ♪

    class Program
    {
        const int port = 8888;
        static TcpListener listener;
        static void Main(string[] args)
        {
            try
            {
                var aTimer = new System.Timers.Timer();
                aTimer.Interval = 10000;
                aTimer.AutoReset = true;
                aTimer.Start();
    
            listener = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
            listener.Start();
            aTimer.Elapsed += OnTimedEvent;
            Console.WriteLine("Ожидание подключений...");
    
            while (true)
            {
                TcpClient client = listener.AcceptTcpClient();
                ClientObject clientObject = new ClientObject(client);
    
                // создаем новый поток для обслуживания нового клиента
                Thread clientThread = new Thread(new ThreadStart(clientObject.Process));
                clientThread.Start();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            if (listener != null)
                listener.Stop();
        }
    }
    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        // Check file access
        //delete file's old content
        var file = new FileInfo("log.txt");
        try
        {
            //stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
            string[] lines = File.ReadAllLines(@"log.txt");
    
    
            StringBuilder newLines = new StringBuilder();
            foreach (var line in lines)
            {
                var date = Convert.ToDateTime(line.Substring(line.IndexOf(' ') + 1));
                var currentTime = DateTime.Now;
                if(date>=currentTime.AddMinutes(-1))
                {
                    newLines.Append(line + "\n");
                }
            }
            Console.WriteLine("Cleaning...");
            using (FileStream fstream = new FileStream("log.txt", FileMode.Create))
            {
                // запись массива байтов в файл
                byte[] array = Encoding.Default.GetBytes(newLines.ToString());
                fstream.Write(array, 0, array.Length);
            }
        }
        catch (IOException)
        {
            //the file is unavailable because it is:
            //still being written to
            //or being processed by another thread
            //or does not exist (has already been processed)
        }
    }
    

    }

    And the ClientObject code

    public class ClientObject
    {
    public TcpClient client;
    public ClientObject(TcpClient tcpClient)
    {
    client = tcpClient;
    }
    public void Process()
    {
    NetworkStream stream = null;
    try
    {
    stream = client.GetStream();
    byte[] data = new byte[64]; // буфер для получаемых данных
    while (true)
    {
    // получаем сообщение
    StringBuilder builder = new StringBuilder();
    int bytes = 0;
    do
    {
    bytes = stream.Read(data, 0, data.Length);
    builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
    }
    while (stream.DataAvailable);

                string message = builder.ToString() + "\n";
    
                Console.WriteLine("Записываю в log {0}", message);
    
                try
                {
                    using (FileStream fstream = new FileStream("log.txt", FileMode.Append))
                    {
                        // преобразуем строку в байты
                        byte[] array = Encoding.Default.GetBytes(message);
                        // запись массива байтов в файл
                        fstream.Write(array, 0, array.Length);
                        //Console.WriteLine("Текст записан в файл");
                    }
                }
                catch(Exception ex)
                {
                    // ERROR MESSAGE TO CLIENT
                    //message = ex.Message;
                    //data = Encoding.Unicode.GetBytes(message);
                    //stream.Write(data, 0, data.Length);
                }
    
                // отправляем обратно сообщение в верхнем регистре
                //message = message.Substring(message.IndexOf(':') + 1).Trim().ToUpper();
                //data = Encoding.Unicode.GetBytes(message);
                //stream.Write(data, 0, data.Length);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            if (stream != null)
                stream.Close();
            if (client != null)
                client.Close();
        }
    }
    

    }



  • Add. Environment.NewLine (or \r\n) Yes, and since you've already found the answer to the question, close it! He hangs on the lists of uninvited people, only came here because of that.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2