【问题标题】:sr.ReadLine() isn't receiving data that is being sentsr.ReadLine() 没有接收到正在发送的数据
【发布时间】:2020-09-13 22:16:15
【问题描述】:

我正在尝试为我的程序实现一种身份验证方法。我有一个处理身份验证的服务器端程序:

    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();
        }
    }

在客户端我有这个代码:

    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;
            }
        }
    }

我已经尝试在客户端和服务器端进行调试。

在客户端,它开始挂在if (sr.ReadLine() == "AFFIRMATIVE")

在服务器端,它开始挂在string line = sr.ReadLine();

我做了一些研究,它告诉我,当 sr.ReadLine() 正在等待数据但没有得到任何数据时,它会一直挂起,直到得到。

但是我已经发送了数据,并且客户端/服务器都无限期地挂起,直到它崩溃。我被卡住了,有人知道为什么这不起作用吗?

【问题讨论】:

  • 尝试在 sw.WriteLine() 之后的客户端代码中添加 sw.Flush()。 StreamReader 有一个内部缓冲区,它不会尝试实际写入,直到您处理流或调用 Flush() 方法

标签: c# .net-core stream network-programming


【解决方案1】:

用你的 sw StreamWriter 写完一条消息后,你需要用sw.Flush(); 刷新它才能真正发送到另一端。

所以

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

否则,您将不会发送任何内容。

【讨论】:

  • 谢谢。我之前调用的是 Stream.Flush 而不是 sw.Flush,但它没有用,所以我尝试摆脱它。谢谢你,它有效!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
相关资源
最近更新 更多