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

时间:2013-12-24 05:30:54

标签: c# asynchronous tcplistener

我有一个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);
    }

}

0 个答案:

没有答案