Esempio n. 1
0
        // User processing
        public void Process()
        {
            try
            {
                Stream = client.GetStream();
                // receiving user's Id
                string message = GetMessage();
                message = Id + " joined the chat.";

                // send message to server about our presence
                server.BroadcastMessage("\n//------------NEW USER ONLINE--------------//\n", this.Id);
                server.BroadcastMessage(message, this.Id);
                server.BroadcastMessage("\n//-------------------------------//\n", this.Id);

                // show message on server console
                Console.WriteLine("\n//------------NEW USER ONLINE--------------//");
                Console.WriteLine(message);
                Console.WriteLine("//-------------------------------//\n");

                // receiving messages from users
                while (true)
                {
                    try
                    {
                        message = GetMessage();

                        if (message.Length == 0)
                        {
                            // if '/disconnect' was typed (disconnect current user from chat)
                            Leave(this.Id);
                            break;
                        }

                        // show message on console
                        message = String.Format("{0}: {1} (ONLINE: {2} users)", Id,
                                                message, server.OnlineClients().ToString());
                        Console.WriteLine(message);
                        server.BroadcastMessage(message, this.Id);
                    }
                    catch
                    {
                        Leave(this.Id);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                // in case of user's disconnection remove all resources
                server.RemoveConnection(this.Id);
                Close();
            }
        }