With the code below I’m getting: “The name ‘listener’ does not exist in the current context”
Really? Why?
static void ReceiveSocketMsgs()
{
try
{
TcpListener listener;
listener = new TcpListener(IPAddress.Any, MainForm.GOHRFTrackerMainForm.socketPortNum);
listener.Start();
using (TcpClient c = listener.AcceptTcpClient())
{
using (NetworkStream n = c.GetStream())
{
string msg = new BinaryReader(n).ReadString();
BinaryWriter w = new BinaryWriter(n);
w.Write(msg + " received");
w.Flush(); // Must call Flush because we're not disposing the writer.
}
}
}
catch (Exception ex)
{
//some exception (if you close the app, it will be "threadabort")
}
finally
{
listener.Stop();
}
}
That’s just how C# scoping works. It does get in the way in
lockstatements andtry/catchclauses. Just move the declaration outside:To keep the listener initialization inside the
tryblock, initialize the variable to null and check that before callingStop.Fixed the initialisation. Well spotted BoltClock.