Click here to Skip to main content
15,851,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a C# application which listens for incoming TCP connections and receive data from previously accepted connections. Please help me whether i use Threadpool or Async methods to write the program?? Note that, once a connection is accepted, it doesn't close it and continuously receive data from the connection, at the same time it accept more connections

Here is my code using ThreadPool

My ThreadPoolTcpSrvr class

C#
public class ThreadPoolTcpSrvr
    {
        private TcpListener client;
        string logTxt = string.Empty;
 
        public ThreadPoolTcpSrvr()
        {
            try
            {
                int port = Convert.ToInt32(AppConfig.PortConfig);
 
                client = new TcpListener(IPAddress.Any, port);
                client.Start();
 
                logTxt = String.Format("Listening to Port {0}...", port);
                ConnectionThread.Log(LoggerEnums.LogLevel.Activity, LoggerEnums.LogType.Common, logTxt);
 
                while (true)
                {
                    while (!client.Pending())
                    {
                        Thread.Sleep(1000);
                    }
                    ConnectionThread newconnection = new ConnectionThread();
                    newconnection.threadListener = this.client;
                    //newconnection.client = client.AcceptTcpClient();
                    ThreadPool.QueueUserWorkItem(new
                               WaitCallback(newconnection.HandleConnection));
                }
            }
            catch (Exception ex)
            {
                logTxt = ex.Message;
                ConnectionThread.Log(LoggerEnums.LogLevel.Error, LoggerEnums.LogType.Common, logTxt);
                Console.ReadLine();
            }
        }
    }


ConnectionThread class
C#
class ConnectionThread
    {
        public TcpListener threadListener;
        private static int connections = 0;
        string logTxt = string.Empty;
        Queue<byte[]> ds = new Queue<byte[]>();
        //public TcpClient client;

        public void HandleConnection(object state)
        {
            try
            {
                int readTimout = AppConfig.ReadTimout;
                TcpClient client = threadListener.AcceptTcpClient();
                IPEndPoint ipep = client.Client.RemoteEndPoint as IPEndPoint;
                IPAddress clientIp = ipep.Address;
                logTxt = String.Format("Accepted connection from {0}...", clientIp);
                Log(LoggerEnums.LogLevel.Activity, LoggerEnums.LogType.Common, logTxt);
                ServerManager s = new ServerManager(threadListener, client);
                NetworkStream ns = client.GetStream();
 
                while (client.Connected)
                {
                    byte[] length = new byte[4];
                    // if (s.ReadData(4, 1000, out length))
                    {
                        int rcvLenght = 232;//216;
                        byte[] data = new byte[rcvLenght];
                        if (s.ReadData(rcvLenght, readTimout, out data))
                        {
                            logTxt = String.Format("Active connection from {0}...", clientIp);
                            Log(LoggerEnums.LogLevel.Activity, LoggerEnums.LogType.Common, logTxt);
 
                            logTxt = String.Format("{0} bytes of data reveived from {1}", rcvLenght, clientIp);
                            Log(LoggerEnums.LogLevel.Activity, LoggerEnums.LogType.Common, logTxt);
 
                            string file = s.SaveBase64Packet(data);
                            logTxt = String.Format("Data saved at {0}", file);
                            Log(LoggerEnums.LogLevel.Activity, LoggerEnums.LogType.Common, logTxt);
                        }
                        else
                        {
                            logTxt = s.Error;
                            Log(LoggerEnums.LogLevel.Error, LoggerEnums.LogType.Common, logTxt);
                        }
                    }
                }
                s.CloseClient();
                if (!client.Connected)
                {
                    logTxt = String.Format("Client {0} disconnected....", clientIp);
                    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 static 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
Updated 18-Dec-13 22:04pm
v2
Comments
Szymon Roslowski 29-Jan-14 10:47am    
Check This :

http://www.codeproject.com/Articles/153938/A-Complete-TCP-Server-Client-Communication-and-RMI

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