paj7777 paj7777 - 9 days ago 5
C# Question

TCP listener stops listening

We currently have a TCP Listener hosted in a windows service. It appears to stop listening at some random interval and, obviously, when a client subsequently makes a request it gets refused. I have tried taking all the Tasks out and the problem still persists. No exception is thrown and consequently nothing is written to the Event Log.

public void Run()
{
var tcpDetail = Task.Run(() => _settingsHelper.GetTcpDetail());

if (tcpDetail != null)
{
var listener = new TcpListener(tcpDetail.Result.ListeningAddress, tcpDetail.Result.ListeningPort);

listener.Start();

while (true)
{
var tcpClient = listener.AcceptTcpClient();

try
{
Task.Run(() => ProcessClient(tcpClient));

}
catch (Exception ex)
{
EventLog.WriteEntry(AppDomain.CurrentDomain.FriendlyName, ex.Message);
if (tcpClient.Client != null && tcpClient.Connected)
{
tcpClient.Close();
}
}
}
}
}


private void ProcessClient(TcpClient client)
{
try
{
var networkStream = client.GetStream();
var reader = new StreamReader(networkStream);


var networkStream = client.GetStream();
var reader = new StreamReader(networkStream);

var request = reader.ReadToEnd();

if (!string.IsNullOrEmpty(request))
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(request);
_someService.Execute(xmlDocument);
}

}
catch (Exception ex)
{
EventLog.WriteEntry(AppDomain.CurrentDomain.FriendlyName, ex.Message);
if (client.Client != null && client.Connected)
{
client.Close();
}
}
finally
{
if (client.Client != null && client.Connected)
{
client.Close();
}
}
}

Answer

It turns out that this behaviour was occurring due to the service being restarted and I was stopping the listening. Making a call to stopping the listener in the OnStop function solved the issue.