Exemple #1
0
        /// <summary>
        /// Gets or send some messages from/to clients.
        /// </summary>
        public void Process()
        {
            try
            {
                Stream = client.GetStream();
                string message = GetMessage();

                username = message;
                message  = username + " is online.";


                // Broadcast all last messages for new User
                Thread.Sleep(500);
                try
                {
                    using (StreamReader sr = new StreamReader(filePath, Encoding.Default))
                    {
                        string text;
                        while ((text = sr.ReadLine()) != null)
                        {
                            text = string.Concat(text, '\n');

                            server.BroadcastForNewUser(text, this.Id);
                        }
                    }
                }
                catch
                {
                    Console.WriteLine("Server: File is empty.");
                }
                // Send to all users the user is online
                server.Broadcast(message, this.Id);

                while (true)
                {
                    try
                    {
                        message = GetMessage();
                        message = string.Format($"{username}: {message}");
                        Console.WriteLine(message);

                        // Write message to /file.txt/
                        using (StreamWriter sw = new StreamWriter(filePath, true, Encoding.Default))
                        {
                            sw.WriteLine($"Last message: {message}");
                        }

                        server.Broadcast(message, this.Id);
                    }
                    catch
                    {
                        message = string.Format($"{username} has left the chat.".ToUpper());
                        Console.WriteLine(message);
                        server.Broadcast(message, this.Id);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                server.RemoveConnection(this.Id);
                Close();
            }
        }