C#TcpListener异步调用在一段时间后未接收数据

C#TcpListener异步调用在一段时间后未接收数据,c#,asynchronous,tcplistener,C#,Asynchronous,Tcplistener,我有一个c#Tcp侦听程序,它侦听传入的连接,并在15秒的时间间隔内从已接受的连接接收数据。但我的应用程序在有时甚至连连接都没有关闭后也没有收到任何数据 这是我的代码 class Listener { string logTxt = string.Empty; TcpListener listener; public event EventHandler Error; List<Client> connectedClients = new List&l

我有一个c#Tcp侦听程序,它侦听传入的连接,并在15秒的时间间隔内从已接受的连接接收数据。但我的应用程序在有时甚至连连接都没有关闭后也没有收到任何数据

这是我的代码

class Listener
{
    string logTxt = string.Empty;
    TcpListener listener;
    public event EventHandler Error;
    List<Client> connectedClients = new List<Client>();

    public Listener()
    {
        try
        {
            int port = Convert.ToInt32(AppConfig.PortConfig);

            listener = new TcpListener(IPAddress.Any, port);
            listener.Start();
            listener.BeginAcceptTcpClient(AcceptTcpClientCallback, null);
            logTxt = String.Format("Listening to Port {0}...", port);
            ConnectionThread.Log(LoggerEnums.LogLevel.Activity, LoggerEnums.LogType.Common, logTxt);
        }
        catch (Exception ex)
        {
            Console.Beep(5000, 2000);
            logTxt = ex.Message;
            Log(LoggerEnums.LogLevel.Error, LoggerEnums.LogType.Common, logTxt);
            Console.ReadLine();
        }
        Console.ReadLine();
        Console.ReadLine(); Console.ReadLine(); Console.ReadLine();
    }

    void AcceptTcpClientCallback(IAsyncResult asyncresult)
    {
        TcpClient tcpClient;
        try
        {
            tcpClient = listener.EndAcceptTcpClient(asyncresult);
        }
        catch (Exception ex)
        {
            Console.Beep(5000, 2000);
            logTxt = ex.Message;
            Log(LoggerEnums.LogLevel.Error, LoggerEnums.LogType.Common, logTxt);

            OnError(listener, ex);
            return;
        }
        listener.BeginAcceptTcpClient(AcceptTcpClientCallback, null);
        Client client = new Client(tcpClient);
        connectedClients.Add(client);

        IPEndPoint ipep = client.TcpClient.Client.RemoteEndPoint as IPEndPoint;
        IPAddress clientIp = ipep.Address;
        logTxt = String.Format("Active connection from {0}...", clientIp);
        Log(LoggerEnums.LogLevel.Activity, LoggerEnums.LogType.Common, logTxt);

        NetworkStream networkStream = client.NetworkStream;
        networkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client);
    }

    public void OnError(object sender, Exception ex)
    {
        EventHandler handler = Error;
        if (handler != null)
        {
            ErrorEventArgs e = new ErrorEventArgs(ex);
            handler(sender, e);
        }
    }

    void ReadCallback(IAsyncResult asyncResult)
    {
        try
        {
            Client client = asyncResult.AsyncState as Client;
            if (client != null)
            {
                NetworkStream networkStream = client.NetworkStream;
                int read;
                try
                {
                    read = networkStream.EndRead(asyncResult);
                }
                catch (Exception ex)
                {
                    OnError(client, ex);
                    return;
                }

                if (read == 0)
                {
                    OnClientDisconnected(client.TcpClient);
                    connectedClients.Remove(client);
                    return;
                }

                byte[] data = new byte[read];
                Buffer.BlockCopy(client.Buffer, 0, data, 0, read);
                OnDataRead(client.TcpClient, data);
                //byte[] ret = BitConverter.GetBytes(1);
                //networkStream.Write(ret, 0, ret.Length); 
                networkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client);
            }
        }
        catch (Exception ex)
        {
            Console.Beep(5000, 2000);
            logTxt = ex.Message;
            Log(LoggerEnums.LogLevel.Error, LoggerEnums.LogType.Common, logTxt);
            //Console.ReadLine();
        }
    }

    private void OnClientDisconnected(TcpClient tcpClient)
    {
        IPEndPoint ipep = tcpClient.Client.RemoteEndPoint as IPEndPoint;
        IPAddress clientIp = ipep.Address;
        logTxt = String.Format("Client {0} disconnected....", clientIp);
        Log(LoggerEnums.LogLevel.Activity, LoggerEnums.LogType.Common, logTxt);
    }

    private void OnDataRead(TcpClient tcpClient, byte[] data)
    {
        try
        {
            IPEndPoint ipep = tcpClient.Client.RemoteEndPoint as IPEndPoint;
            IPAddress clientIp = ipep.Address;
            logTxt = String.Format("{0} bytes of data reveived from {1}", data.Length, clientIp);
            Log(LoggerEnums.LogLevel.Activity, LoggerEnums.LogType.Common, logTxt);

            ServerManager s = new ServerManager();
            string file = s.SaveBase64Packet(data);
            logTxt = String.Format("Data saved at {0}", file);
            Log(LoggerEnums.LogLevel.Activity, LoggerEnums.LogType.Common, logTxt);
        }
        catch (Exception ex)
        {
            Console.Beep(5000, 2000);
            logTxt = ex.Message;
            Log(LoggerEnums.LogLevel.Error, LoggerEnums.LogType.Common, logTxt);
            //Console.ReadLine();
        }
    }

    public void Log(LoggerEnums.LogLevel logLevel, LoggerEnums.LogType logType, string text)
    {
        string log = LogManager.FormatString(logLevel, text);
        Console.Write(log + Environment.NewLine);
        LogManager.WriteLog(logLevel, logType, text);
    }

}
类侦听器
{
string logTxt=string.Empty;
听者;
公共事件事件处理程序错误;
List connectedClients=new List();
公共侦听器()
{
尝试
{
int port=Convert.ToInt32(AppConfig.PortConfig);
侦听器=新的TcpListener(IPAddress.Any,端口);
listener.Start();
BeginAcceptTcpClient(AcceptTcpClientCallback,null);
logTxt=String.Format(“侦听端口{0}…”,端口);
ConnectionThread.Log(LoggerEnums.LogLevel.Activity、LoggerEnums.LogType.Common、logTxt);
}
捕获(例外情况除外)
{
控制台。哔哔声(5000,2000);
logTxt=例如消息;
日志(LoggerEnums.LogLevel.Error、LoggerEnums.LogType.Common、logTxt);
Console.ReadLine();
}
Console.ReadLine();
Console.ReadLine();Console.ReadLine();Console.ReadLine();
}
无效AcceptCpclientCallback(IAsyncResult asyncresult)
{
TCP客户机TCP客户机;
尝试
{
tcpClient=listener.EndAcceptTcpClient(asyncresult);
}
捕获(例外情况除外)
{
控制台。哔哔声(5000,2000);
logTxt=例如消息;
日志(LoggerEnums.LogLevel.Error、LoggerEnums.LogType.Common、logTxt);
OnError(监听器,ex);
返回;
}
BeginAcceptTcpClient(AcceptTcpClientCallback,null);
客户=新客户(tcpClient);
connectedClients.Add(客户端);
IPEndPoint ipep=client.TcpClient.client.RemoteEndPoint作为IPEndPoint;
IPAddress clientIp=ipep.Address;
logTxt=String.Format(“来自{0}的活动连接…”,clientIp);
日志(LoggerEnums.LogLevel.Activity、LoggerEnums.LogType.Common、logTxt);
NetworkStream NetworkStream=client.NetworkStream;
networkStream.BeginRead(client.Buffer,0,client.Buffer.Length,ReadCallback,client);
}
public void OnError(对象发送方,异常示例)
{
EventHandler=错误;
if(处理程序!=null)
{
ErrorEventArgs e=新的ErrorEventArgs(ex);
处理人(发送者,e);
}
}
void ReadCallback(IAsyncResult asyncResult)
{
尝试
{
客户端=asyncResult.AsyncState作为客户端;
如果(客户端!=null)
{
NetworkStream NetworkStream=client.NetworkStream;
int-read;
尝试
{
read=networkStream.EndRead(异步结果);
}
捕获(例外情况除外)
{
OnError(客户,ex);
返回;
}
如果(读==0)
{
一旦客户端断开连接(client.TcpClient);
已连接的客户端。删除(客户端);
返回;
}
字节[]数据=新字节[读取];
Buffer.BlockCopy(client.Buffer,0,data,0,read);
OnDataRead(client.TcpClient,数据);
//byte[]ret=BitConverter.GetBytes(1);
//networkStream.Write(ret,0,ret.Length);
networkStream.BeginRead(client.Buffer,0,client.Buffer.Length,ReadCallback,client);
}
}
捕获(例外情况除外)
{
控制台。哔哔声(5000,2000);
logTxt=例如消息;
日志(LoggerEnums.LogLevel.Error、LoggerEnums.LogType.Common、logTxt);
//Console.ReadLine();
}
}
客户端断开连接时的私有无效(TCP客户端TCP客户端)
{
IPEndPoint ipep=tcpClient.Client.RemoteEndPoint作为IPEndPoint;
IPAddress clientIp=ipep.Address;
logTxt=String.Format(“客户端{0}已断开连接…”),clientIp;
日志(LoggerEnums.LogLevel.Activity、LoggerEnums.LogType.Common、logTxt);
}
私有void OnDataRead(TcpClient TcpClient,字节[]数据)
{
尝试
{
IPEndPoint ipep=tcpClient.Client.RemoteEndPoint作为IPEndPoint;
IPAddress clientIp=ipep.Address;
logTxt=String.Format(“{1}接收的数据的{0}字节”,data.Length,clientIp);
日志(LoggerEnums.LogLevel.Activity、LoggerEnums.LogType.Common、logTxt);
ServerManager s=新的ServerManager();
字符串文件=s.savebase64数据包(数据);
logTxt=String.Format(“数据保存在{0}”,文件);
日志(LoggerEnums.LogLevel.Activity、LoggerEnums.LogType.Common、logTxt);
}
捕获(例外情况除外)
{
控制台。哔哔声(5000,2000);
logTxt=例如消息;
日志(LoggerEnums.LogLevel.Error、LoggerEnums.LogType.Common、logTxt);
//Console.ReadLine();
}
}
公共无效日志(LoggerEnums.LogLevel LogLevel、LoggerEnums.LogType LogType、字符串文本)
{
string log=LogManager.FormatString(日志级别,文本);
Console.Write(log+Environment.NewLine);
LogManager.WriteLog(日志级别、日志类型、文本);
}
}