【发布时间】: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