我正在学习如何使用下面的简单示例加密网络流。在没有加密的情况下,这个例子工作得很好,但是现在我添加了 CryptoStreams,在客户端写入消息并刷新后,服务器挂在“var data = reader.ReadLine()”上。
static byte[] Key;
static byte[] IV;
static void Main(string[] args)
{
var svrTask = RunServer();
RunClient();
svrTask.Wait();
}
static async Task RunServer ()
{
var listener = new TcpListener(4567);
var algo = new RijndaelManaged();
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
using (var inputStream = new CryptoStream(stream, algo.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
using (var outputStream = new CryptoStream(stream, algo.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
var reader = new StreamReader(inputStream);
var writer = new StreamWriter(outputStream);
var data = reader.ReadLine(); // Task hangs here
writer.WriteLine("Server Received: " + data);
writer.Flush();
}
client.Close();
listener.Stop();
}
static void RunClient ()
{
var algo = new RijndaelManaged();
Key = algo.Key;
IV = algo.IV;
var client = new TcpClient("localhost", 4567);
using (var stream = client.GetStream())
using (var inputStream = new CryptoStream(stream, algo.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
using (var outputStream = new CryptoStream(stream, algo.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
var writer = new StreamWriter(outputStream);
Console.WriteLine("Client will send: ");
var data = Console.ReadLine();
writer.WriteLine(data);
writer.Flush();
var reader = new StreamReader(inputStream);
var response = reader.ReadLine();
Console.WriteLine("Client received: " + response);
}
}
我很确定我错过了一些非常简单的东西。首先想到的是加密会扰乱新行字符的发送,导致服务器在等待分隔符时挂起,但我无法发现问题。
任何帮助,将不胜感激。