I've made an application that communicates via a second application TCP and I get an error:
System.NullReferenceException: 'Object reference not set to an instance of an object.' --> s was null at the while loop.
This error only occurs when I forcefully close the second application (By pressing the X at the top of the app or killing it via task manager) that is still connected with the first one.
My first application that receives commands and prints them out:
try
{
StreamReader reader = new StreamReader(client.GetStream());
StreamWriter writer = new StreamWriter(client.GetStream());
string s = String.Empty;
while (!(s = reader.ReadLine()).Equals("PING"))
Console.WriteLine(s);
reader.Close();
writer.Close();
client.Close();
}
catch (IOException)
{
Console.WriteLine("woops an error!");
}
My second application that sends the commands:
try
{
TcpClient client = new TcpClient("192.168.0.107", 8080);
StreamReader reader = new StreamReader(client.GetStream());
StreamWriter writer = new StreamWriter(client.GetStream());
writer.WriteLine("PING");
writer.Flush();
reader.Close();
writer.Close();
client.Close();
}catch(Exception ex)
Console.WriteLine(ex.Message);
I tried checking if s==null(like below) and it still throws an exception.
while (!(s = reader.ReadLine()).Equals("PING") || (s==null))