sr.ReadLine() isn’t receiving data that is being sent

I am trying to implement an authentication method for my program. I have a server-side program that handles authentication:

    class Program
    {
        static TcpListener listener = new TcpListener(9120);
        public const string DECRYPT_KEY = "KObOBonONoinbOClHNKYJkgIKUFkjfKcvCYckcvBBCVKcbvHHCxthjcTJYBXJahjh";

        static void Main(string[] args)
        {
            listener.Start();
            while (true)
            {
                if (listener.Pending())
                {
                    new Thread(TryAuthenticate).Start();
                }
            }
        }

        static void TryAuthenticate()
        {
            TcpClient needsAuth = listener.AcceptTcpClient();

            StreamReader sr = new StreamReader(needsAuth.GetStream());
            string line = sr.ReadLine();
            if (!line.StartsWith("AUTH? ")) return;

            StreamReader sr2 = new StreamReader("keys.pks");

            string line2;

            while ((line2 = sr2.ReadLine()) != null)
            {
                if (line == line2)
                {
                    new StreamWriter(needsAuth.GetStream()).WriteLine("AFFIRMATIVE");
                    sr.Close();
                }
            }

            sr2.Close();
            needsAuth.Close();
        }
    }

And on the client-side I have this code:

    class Authentication
    {
        public static bool Authenticate(string id)
        {
            if (id == "dEbUg2020") return true;

            TcpClient client = new TcpClient("127.0.0.1", 9120);
            StreamWriter sw = new StreamWriter(client.GetStream());
            StreamReader sr = new StreamReader(client.GetStream());
            sw.WriteLine("AUTH? " + id);
            if (sr.ReadLine() == "AFFIRMATIVE")
            {
                sw.Close();
                sr.Close();
                client.Close();
                return true;
            }
            else
            {
                sw.Close();
                sr.Close();
                client.Close();
                return false;
            }
        }
    }

I have tried debugging on both the client and the server side.

On the client-side, it starts hanging at if (sr.ReadLine() == "AFFIRMATIVE").

On the server-side, it starts hanging at string line = sr.ReadLine();.

I have done some research and it has told me that when sr.ReadLine() is expecting data but doesn’t get any, it hangs until it does.

But I have sent data, and both the client/server hangs indefinitely until it crashes. I am stuck, does anyone know why this isn’t working?

Answer

After writing a message with your sw StreamWriter, you need to flush it with sw.Flush(); for it to actually be sent to the other side.

So

sw.WriteLine("Some line");
sw.Flush();

Otherwise, you’re not sending anything.

Leave a Reply

Your email address will not be published. Required fields are marked *