lou

lou


  • Name: [not set]
  • Favorite Languages: [not set]
  • Website: [not set]
  • Location: [not set]
  • About Me: [not set]

Recent Comments

  • C# Tutorial - Simple Threaded TCP Server
    05/08/2010 - 11:06

    void main (Hi...arg,events,help)
    {
    i want to save tcpclient in a collection i used Hashtable and then use an array of TcpClient but when server want to send data t specific client with specific ConnectID it say that can not use dispose object
    it means that the tcpclient that i saved in server is disconnected.client.(connected==false) i think my previouse problem has the same source as this is.
    so if im am wrong in saving client how should i do that.and be able to send info from server to specific client.
    [edit post]
    after i post this i found that the thread that this client has run on it(also other client on their own thread) is stoped.and i think this is the source of error 10053 software in you host disconnect you.(sth like that).but i dont know why the threds stop afterward.and i also geuss it might be time out problem as you sais it is finite but as i trace and load connection from collectio at first it is connect but after seconds as i stay in Isend() it will disconnect and my stream writer can not write to dispose object so if the problem is from timeout how should i do that.
    so any buddy has any idea,
    thanx 4 ur help;

    and here is the code.

    }
    here is my server class and send function

        class Server : packetizer
        {
            #region Variable Scope
            private Socket socket;
            private TcpListener tcpListener;
            private Thread listenThread;
            private Queue thread_Queue;//it keep thread id inorder to dispose after disconnection
            private delegate void setText(string str);
            private TextBox Logger;
            private static int ConnectID;
            private Connection_State CS;
            #endregion

            public Server(TextBox logger,Connection_State cs) //Constructor
            {
                Logger = logger;
                CS = cs;
            }
           
            public void start_Server() //Point to start Server
            {
                this.tcpListener = new TcpListener(IPAddress.Any, 1313);
                this.listenThread = new Thread(new ThreadStart(ListenForClients));
                this.listenThread.Start();
            }
           
            private void ListenForClients()
            {
                this.tcpListener.Start();
                Invoking_Logger("Server startlistenning...");
                thread_Queue = new Queue();
                TcpClient client = null;
                while (true)
                {
                    try
                    {
                        //blocks until a client has connected to the Server
                        client = this.tcpListener.AcceptTcpClient();
                    }
                    catch (SocketException ex)
                    {
                        break;
                    }
                   
                    //create a thread to handle communication
                    //with connected client
                    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                    //thread_Queue.Enqueue(clientThread);
                   
                    clientThread.Start(client);
                   
                    socket = client.Client;
                    CS.ClientHolder.structSocket = client.Client;
                    CS.ClientHolder.structThread=clientThread;
                    CS.ClientHolder.structTcpClient = client;
                    CS.Add_To_Acp_Client((ConnectID+1), CS.ClientHolder);

                    Invoking_Logger("Client with below information registerd to server:\r\n" +
                        ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString() + "::" + ((IPEndPoint)(socket.RemoteEndPoint)).Port.ToString()+"\r\n"+
                         "SocketType: " + socket.SocketType.ToString() +"\r\n" +SocketOptionLevel.Socket.ToString() + " " +SocketOptionName.IPOptions.ToString());
                }
            }

            private void HandleClientComm(object client)
            {
                TcpClient tcpClient = (TcpClient)client;
                NetworkStream clientStream = tcpClient.GetStream();
                Packet rcvPacket = new Packet();
                Packet sendPacket = new Packet();
                IPEndPoint ipe = (IPEndPoint)tcpClient.Client.LocalEndPoint;
               
                byte[] DataToSend;
                byte[] message = new byte[tcpClient.ReceiveBufferSize];
                int bytesRead;

                while (true)
                {
                    bytesRead = 0;

                    try
                    {
                        //blocks until a client sends a message
                        bytesRead = clientStream.Read(message, 0, 4096);
                    }
                    catch
                    {
                        //a socket error has occured
                        break;
                    }

                    if (bytesRead == 0)
                    {
                        //the client has disconnected from the Server
                        break;
                    }
                   
                    //---get the message---
                    byte[] buff;
                    string MessageReceived =
                        ASCIIEncoding.ASCII.GetString(message, 0, bytesRead);
                    rcvPacket = (Packet)RawDeserialize(message);

                    Invoking_Logger(MessageReceived.ToString());

                    switch (rcvPacket.Type)
                    {
                        case "0"://It is usual msg 4 Connection
                            if (rcvPacket.ProcID == -1)
                            {
                                try
                                {
                                    Interlocked.Increment(ref ConnectID);
                                    sendPacket.Type = "1";
                                    sendPacket.Message = "You have registerd";//CS.Get_INFO;
                                    sendPacket.IP_Addr = Convert.ToString(ipe.Address);
                                    sendPacket.Port_NO = ipe.Port;
                                    sendPacket.ProcID = ConnectID; //CS.Set_ConnectID;
                                    DataToSend = RawSerialize(sendPacket);//ASCIIEncoding.ASCII.GetBytes(t);
                                    tcpClient.GetStream().Write(DataToSend, 0, DataToSend.Length);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("Item Exist");
                                }
                             
                            }
                            break;
                        case "1"://Ack msg
                            break;
                        case "2"://register for Item processing

                            bool bol = false;
                           
                            break;

                        case "UDP_BroadCast":
                            break;
                        default: break;
                    }
                    //message has successfully been received
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
                }

                tcpClient.Close();
            }
            public void Isend(int ConnectID)
            {
                Socket SockettcpClient=null;
                TcpClient tcpClient = null;
                CData cData=new CData() ;
                Packet pck_Test = new Packet();
                pck_Test.Type = "1";
                pck_Test.Message = "test message";
                byte[] buffer = RawSerialize(pck_Test);
                try
                {
                   cData=(CData) CS.Find_In_Acp_Client(ConnectID);
                   
                }
                catch (Exception ex)
                { }
                tcpClient =(TcpClient) cData.structTcpClient;
                Thread thrd = cData.structThread;
                thrd.Start();
                NetworkStream clientStream = tcpClient.GetStream();
                //ASCIIEncoding encoder = new ASCIIEncoding();
                //byte[] buffer = encoder.GetBytes("Hello Client!");

                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
                clientStream.Close();
            }

    and here is COnnection stat class that hols my client information to reconnect to them i

     

     public struct CData
        {
            public Socket structSocket;
            public TcpClient structTcpClient;
            public Thread structThread;
        }


        class Connection_State
        {
            #region Variable Scope
            private Hashtable Accepted_Client = new Hashtable();
            public CData ClientHolder = new CData();
            #endregion

            public Connection_State()
            {

            }

            public Hashtable Acp_Client
            {
                get { return Accepted_Client; }
                set { Accepted_Client = value; }
            }

            //Add new client that connect to sever to this HashTable
            public void Add_To_Acp_Client(int ConnectID, CData structtcpthread)
            {
                Accepted_Client.Add(ConnectID, structtcpthread);
            }
    }

  • C# Tutorial - Simple Threaded TCP Server
    05/07/2010 - 14:58

    Thank you very much.

  • C# Tutorial - Simple Threaded TCP Server
    05/06/2010 - 15:16

    Hi,thanx for your good tutorial.

    here is question as Nigel asked it long ago. i have the same problem.and i could not fine the answer,can any body help me.

    I have an application which is essentially a TCP/IP Server to which up to 16 clients can connect at any one time each on it's own unique port, i.e. 4001 - 4016.

    The connections establish ok but after a period of time the connections seem to disconnect and I'm not sure why. when you run NETSTAT from the DOS Prompt it shows the connections in a CLOSE_WAIT state.

    The clients then have to reconnect... and so the loop goes on...

    Whe I try to write back to the client and it is disconnected I get an error code of 10053 which means that the software in the host machine has disconnected or something along those lines.

    Has anyone else had experience of this? Could it be a timeout? How can I ensure that once my server accepts a client connection that it helps to maintain the established connection?

    Any and all help appreciated.

    Nigel.