My dual-role app (in its role as "Server" running on another machine) fails to actually shut down when I close it (it is still in the "Processes" list in Task Manager after I close the app).
I don't know if it is staying "live" because its TcpListener class is still listening, or if the TcpListener class is still listening because the app hasn't really shut down.
So, I added two pieces of code:
1) The last line here (listener.Stop()):
static void Server()
{
TcpListener listener = new TcpListener(IPAddress.Any, 51111);
listener.Start();
var shouldExit = false;
while (!shouldExit)
using (TcpClient c = listener.AcceptTcpClient())
{
using (NetworkStream n = c.GetStream())
{
string msg = new BinaryReader(n).ReadString();
if (msg == "exit")
// Client told us to exit...
shouldExit = true;
BinaryWriter w = new BinaryWriter(n);
w.Write(msg + " back atcha!");
w.Flush(); // Must call Flush because we're not disposing the writer.
}
}
//listener.EndAcceptTcpClient; //unnecessary because AcceptTcpClient() is wrapped in a "using"?
listener.Stop();
}
...and:
2)
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Close(); // The app/process is staying "live" even after shutting down the app...maybe this will help?
}
// but on closing the app, I got: "System.StackOverflowException was unhandled" here...?
Why would there be a Stack overflow when calling Close?