Click here to Skip to main content
15,898,968 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a c# Tcp listener program that listens for incoming connections and receive data from accepted connections during 15 second interval. But my application is not receiving any data after sometimes even the connection is not closed.

Here is my code

C#
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);
    }

}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900