Отправка сообщения от сервера клиенту на консоль - C#
Формулировка задачи:
Ребят, подскажите пожалуйста, в момент удачной записи данных в файл (на стороне сервера выполняется запись в файл), нужно клиенту от сервера отправить на консоль сообщение что все ОК, или ERROR, в случае непредвиденных событий.. В коде клиента в классе TcpWriter я определил метод Response(), а в коде сервера в классе ClientObjects в блоке try пишу:
В итоге мне в консоль клиента выводится только 1 раз сообщение "Успешно". А должно выводить:
Успешно
Успешно
Успешно
...........
Код сервера:
и код клиента
Спасибо заранее!
Листинг программы
- string sendmsg = "Успешно";
- data = Encoding.Unicode.GetBytes(sendmsg);
- stream.Write(data, 0, data.Length);
Листинг программы
- namespace Server
- {
- 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() + "\r\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);
- }
- string sendmsg = "Успешно";
- data = Encoding.Unicode.GetBytes(sendmsg);
- stream.Write(data, 0, data.Length);
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- finally
- {
- if (stream != null)
- stream.Close();
- if (client != null)
- client.Close();
- }
- }
- }
- }
- namespace Server
- {
- class Program
- {
- const int port = 8888;
- static TcpListener listener;
- static void Main(string[] args)
- {
- try
- {
- var aTimer = new System.Timers.Timer();
- //65454
- aTimer.Interval = 65500;
- 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;
- double minuts = -1;
- if(date>=currentTime.AddMinutes(minuts))
- {
- newLines.Append(line + "\r\n");
- }
- }
- Console.WriteLine("Cleaning...");
- using (FileStream fstream = new FileStream("log.txt", FileMode.Create))
- {
- // запись массива байтов в файл
- byte[] array = Encoding.Default.GetBytes(newLines.ToString() + "\r\n");
- 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)
- }
- }
- }
- }
Листинг программы
- namespace Client
- {
- class TcpWriter
- {
- TcpClient client;
- NetworkStream stream;
- int packNum = 0;
- int maxPackNum;
- public TcpWriter(int port, string address, int maxPackNum)
- {
- client = new TcpClient(address, port);
- stream = client.GetStream();
- this.maxPackNum = maxPackNum;
- }
- public void Response()
- {
- byte[] data = new byte[64]; // буфер для получаемых данных
- 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 msg = builder.ToString();
- Console.WriteLine("Сервер: {0}", msg);
- }
- public void Run()
- {
- System.Timers.Timer myTimer = new System.Timers.Timer();
- myTimer.Elapsed += new ElapsedEventHandler(MessageEvent);
- myTimer.Interval = 1000;
- myTimer.Start();
- Response();
- }
- public void MessageEvent(object source, ElapsedEventArgs e)
- {
- string message = string.Format("{0}: {1}", packNum++, DateTime.Now);
- byte[] data = Encoding.Unicode.GetBytes(message);
- stream.Write(data, 0, data.Length);
- if (packNum > maxPackNum)
- {
- (source as System.Timers.Timer).Stop();
- client.Close();
- }
- }
- }
- }
- namespace Client
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- TcpWriter tcpWriter = new TcpWriter(8888, "127.0.0.1", 1000);
- tcpWriter.Run();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- Console.ReadLine();
- }
- }
- }
Решение задачи: «Отправка сообщения от сервера клиенту на консоль»
textual
Листинг программы
- for (; ; )
- Response();
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д