I am trying to create a client-server program that sends and receives a string (this is a simple chat application over a local network).
The program works fine, but I need to encrypt it, and this problem, when I use encryption, it seems that it closes the connection after every moment of sending data, and I need to restart it to receive further messages (which I cannot, because they talk and should constantly)
By the way, I do not mind, even if its weak encryption as long as its text is not accurate.
Here is one side of my program (server):
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();
}
Here is an example of the code I tried to use for encryption: (server) 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, .