TCP侦听器停止侦听

时间:2016-11-25 17:20:30

标签: c# sockets tcp windows-services

我们目前在Windows服务中托管了一个TCP侦听器。它似乎在某个随机间隔停止收听,显然,当客户随后发出请求时会被拒绝。我已经尝试取出所有任务,问题仍然存在。不会抛出任何异常,因此不会将任何内容写入事件日志。

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();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

事实证明,由于重新启动服务并且我正在停止监听,因此发生了此行为。在OnStop函数中调用停止监听器解决了这个问题。