Пример #1
0
        private static void HandleClient(object oclient)
        {
            Client client = (Client)oclient;

            // Buffer for reading data
            byte[] bytes = new byte[256];
            string data;
            // Get a stream object for reading and writing
            NetworkStream stream = client.tcpClient.GetStream();

            int i;

            // Loop to receive all the data sent by the client.
            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                // Translate data bytes to a ASCII string.
                data = Encoding.ASCII.GetString(bytes, 0, i);
                if (data.First() == '~')
                {
                    //the client sent the name
                    client.Name = data.Split('~')[1];
                }
                else if (data.First() == '-')
                {
                    //the client sent a message
                    data = data.Split('-')[1];
                    DetailedMessage dm = data;
                    SendToAll(dm);
                    Console.WriteLine(dm.ToString());
                }
            }

            // Shutdown and end connection
            client.tcpClient.Close();
        }
Пример #2
0
        static void SendToAll(DetailedMessage dm)
        {
            for (int i = 0; i < clients.Count; i++)
            {
                if (clients[i].Name != dm.Name)
                {
                    try
                    {
                        clients[i].tcpClient.GetStream().Write(dm, 0, dm.Length + 1);
                    }
                    catch
                    {
                        string name = clients[i].Name;
                        clients.Remove(clients[i]);
                        i--;
                    }
                }
            }
            //foreach (Client item in clients)
            //{
            //    if (item.Name != dm.Name)
            //    {
            //        try
            //        {
            //            item.tcpClient.GetStream().Write(dm, 0, dm.Length + 1);
            //        }
            //        catch
            //        {
            //            string name = item.Name;
            //            clients.Remove(item);
            //            SendToAll(new DetailedMessage("Server", name + " had exit the chatroom"));
            //        }

            //    }
            //}
        }