Click here to Skip to main content
15,071,262 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I got above exception in my application. that's the reason why data not displayed on text box. anyone help me. I want to run form1 on main UI thread . How to do that?

here is my code,
I have 2 classes , form1 and handleClient.cs . Got exception at AppendTxtdata method at bold line.

here is Form1.cs

C#
namespace connectSuccess
{
    public partial class Form1 : Form
    {
        private handleClient handleClient;
        private bool IsRunning = false;
        TcpListener serverSocket;
        TcpClient clientSocket;
     

        public Form1()
        {
            InitializeComponent();
        }

        public Form1(handleClient handleClient)
        {
            // TODO: Complete member initialization
            this.handleClient = handleClient;
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            string ipaddre = getip();
            IPAddress iP = IPAddress.Parse(ipaddre);
            AppendTxtip(iP.ToString());
        }


        private void btnstart_Click(object sender, EventArgs e)
        {
           new Thread(startServer).Start();
          
        }


        public  void startServer()
        {
            try
            {
                int port = Convert.ToInt32(txtport.Text);
                string ipaddre = getip();
                IPAddress iP = IPAddress.Parse(ipaddre);
                // AppendTxtip(iP.ToString());
                serverSocket = new TcpListener(iP, port);
                clientSocket = default(TcpClient);
                int counter = 0;
                serverSocket.Start();
               AppendTxtdata("Server Started , Waiting for Client Connection" + Environment.NewLine);

                IsRunning = true;

                while (IsRunning)
                {
                    counter += 1;
                    clientSocket = serverSocket.AcceptTcpClient();
                    AppendTxtdata(" >> " + "Client No:" + Convert.ToString(counter) + " Connected-- IP --" + clientSocket.Client.RemoteEndPoint.ToString() + "");
                    AppendTxtdata(Environment.NewLine);
                    handleClient client = new handleClient();
                    client.startClient(clientSocket, Convert.ToString(counter));
                    // break;
                }
               
            }
            catch { }
            finally { }
        }


        public void StopServer()
        {
            IsRunning = false;       
        }


        static string getip() // to get ip addrees of machine on which this app installed //
        {
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());

            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();                
                }
            }
            return localIP;
        }


        public void AppendTxtip(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(AppendTxtip), new object[] { value });
                return;
            }
            txtip.Text += value;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

               AppendTxtdata("Data sent to Client No : " + clientSocket.Client.RemoteEndPoint + Environment.NewLine);
               this.clientSocket.Close();
               this.serverSocket.Stop();
               
            }
            catch { }
        }

       
        public void AppendTxtdata(string myval)
        {
            try
            {
            
                if (InvokeRequired)
                {
                        this.Invoke(new Action<string>(AppendTxtdata), new object[] { myval });
                        return;
                }
                txtdata.Text += myval;
            }
            catch { }
        }
    
    }   
}


here is HandleClient.cs

C#
public class handleClient
{

    public static SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Database1"].ToString());
    SqlCommand cmd;
    DataTable table;
    SqlDataAdapter adapter;
    ASCIIEncoding asen = new ASCIIEncoding();
    TcpClient clientSocket;

    string clNo;
    byte[] coma, star, hash, SQLDATA;


    public void startClient(TcpClient inClientSocket, string clineNo)
    {
        this.clientSocket = inClientSocket;
        inClientSocket.NoDelay = true;
        this.clNo = clineNo;
      //  GetData();
        new Thread(GetData).Start();
    }


    public void GetData() // to run server //
    {
        try
        {
            con.Open();

            Form1 f = new Form1();
            NetworkStream networkStream = clientSocket.GetStream();

            for (int p = 0; p >= 0; p++)
            {
                byte[] b = new byte[100];

                int k = networkStream.Read(b, 0, b.Length);

                f.AppendTxtdata("The Data from Client ( " + clNo + " ) Recieved..." + Environment.NewLine);

                for (int i = 0; i < k; i++)
                {
                    f.AppendTxtdata("" + Convert.ToChar(b[i]));
                }

                f.AppendTxtdata(Environment.NewLine);

                var j = b.Length - 1;
                while (b[j] == 0)
                {
                    --j;
                }

                var temp = new byte[j + 1];
                Array.Copy(b, temp, j + 1);

                string res = System.Text.Encoding.ASCII.GetString(temp);

                switch (res.Substring(0, 1))
                {
                   //all stuff here
                }
            }
        }
        catch { }
        finally { con.Close(); }
    }
}


edited
here is Globalvariable class.

C#
class Globalvariable
   {
       public static string SomeData = "";
   }


here is edited Appendtxtdata method

C#
public void AppendTxtdata(string myval)
{
    try
    {
       // Globalvariable.SomeData += "I am from form 1 \r\n";
        if (InvokeRequired)
        {
            this.Invoke(new Action<string>(AppendTxtdata), new object[] {myval });
            return;
        }
        Globalvariable.SomeData += myval;
    }
    catch { }
    txtdata.Text = Globalvariable.SomeData;

}

Now this shows data in textbox but after stoping server or closing tcpclient and tcplistener objects. but i want to show data without closing those objects how to do this way i.e clicking stop button code is here of stop button,

C#
private void button1_Click(object sender, EventArgs e)
{
    try
    {

        AppendTxtdata("Data sent to Client No : " + clientSocket.Client.RemoteEndPoint + Environment.NewLine);
        this.clientSocket.Close();
        this.serverSocket.Stop();

    }
    catch { }
}
Posted
Updated 25-Jul-15 22:45pm
v4
Comments
Wendelius 26-Jul-15 2:16am
   
What is the code causing the error?
Member 11543226 26-Jul-15 2:24am
   
I added my full code in question please go through it once.
   
Of course it's not full code. Do I even have to show what's not shown? And of course you did not provide comprehensive exception information. I would really advise you to try to answer the questions asked. Remember that you are the one who is interested the most. You could run your code under the debugger and see what's going on.
—SA
Member 11543226 26-Jul-15 2:40am
   
I run this code and textbox doesnt shows any data when AppendTxtdata method runs from handleClient class as it is created on Form1 . No error showing while running only this exception is shown.
Richard MacCutchan 26-Jul-15 3:18am
   
If you want help with this then please show the full exact text of the exception, and mark the point in your code where it occurs. Don't expect people to guess what is happening; we cannot see your screen or read your mind.
Member 11543226 26-Jul-15 4:35am
   
now I modified some code , I created one class Globalvariable. and modified code like above. see edited question.
Richard MacCutchan 26-Jul-15 7:37am
   
No wonder you have problems. Put some proper code inside those catch blocks so you can see when something fails, and help to diagnose the causes.

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