【发布时间】:2011-03-11 17:52:10
【问题描述】:
我正在尝试创建一个发送和接收字符串的客户端-服务器程序(它是一个简单的局域网聊天应用程序)。
程序运行良好,但我需要对其进行加密,这就是问题所在,当我使用加密时,似乎每次发送数据后它都会关闭连接,我需要重新运行它才能接收进一步的消息(我不能,因为它正在聊天,应该不断)
顺便说一句,我不介意即使它是弱加密,只要它不是纯文本就可以。
这是我的程序的一侧(服务器):
public static void Main()
{
string data;
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 9999);
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ip);
socket.Listen(10);
Socket client = socket.Accept();
IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}",newclient.Address, newclient.Port);
NetworkStream ns = new NetworkStream(client);
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
string welcome = "Welcome";
sw.WriteLine(welcome);
sw.Flush();
while(true)
{
data = sr.ReadLine();
Console.WriteLine(data);
sw.WriteLine(data);
sw.Flush();
}
Console.WriteLine("Disconnected from {0}", newclient.Address);
sw.Close();
sr.Close();
ns.Close();
}
这是我尝试用于加密的代码示例:(服务器) IPAddress IP2 = IPAddress.Parse(IP); TcpListener TCPListen = new TcpListener(IP2, port);
TCPListen.Start();
TcpClient TCP = TCPListen.AcceptTcpClient();
NetworkStream NetStream = TCP.GetStream();
RijndaelManaged RMCrypto = new RijndaelManaged();
byte[] Key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
CryptoStream CryptStream = new CryptoStream(NetStream,
RMCrypto.CreateDecryptor(Key, IV),
CryptoStreamMode.Read);
StreamReader SReader = new StreamReader(CryptStream);
message = SReader.ReadToEnd();
textBox3.Clear();
textBox3.Text = message;
CryptStream.Flush();
SReader.Close();
NetStream.Flush();
NetStream.Close();
TCPListen.Stop();
TCP.Close();
我尝试只刷新 netstream 和 cryptstream,以便保持连接打开。
【问题讨论】:
标签: c#