0

My server form accepts connection request from client and then i need to add ip address of connected clients in a list box named lstIP.But im unable to access lstIP from OnClientConnect method.help would be appreciated.Here is the code:

public partial class Form1 : Form
    {
        public int cpuLoad;
        private PerformanceCounter cpuCounter;
      static  public string curIP;
       public static string get_localip = GetLocalIP();

        public Form1()
        {
            InitializeComponent();
            InitialiseCPUCounter();
            timer1.Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            lblServerIP.Text += " "+get_localip;
        }
          private static TcpListener _listener;

           public static void StartServer() 
    {
         System.Net.IPAddress localIPAddress = System.Net.IPAddress.Parse(get_localip);
        IPEndPoint ipLocal = new IPEndPoint(localIPAddress, 8888);
        _listener = new TcpListener(ipLocal);
        _listener.Start();
        WaitForClientConnect();

    }
    private static void WaitForClientConnect()
    {
        object obj = new object();
        _listener.BeginAcceptTcpClient(new System.AsyncCallback(OnClientConnect), obj);
    }
    public static void OnClientConnect(IAsyncResult asyn)
    {
        try
        {

            TcpClient clientSocket = default(TcpClient);
           // Socket sck;


            clientSocket = _listener.EndAcceptTcpClient(asyn);
         IPAddress add= IPAddress.Parse(((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString());
         curIP = add.ToString();

          Form1 myform=new Form1();
          myform.items.add("client connectes with ip:"+curIP);
          **// lstIP.items.add("client connected with ip"+curIP); 
        // MessageBox.Show("cleint connected with ip:"+ curIP);**

            HandleClientRequest clientReq = new HandleClientRequest(clientSocket);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

        WaitForClientConnect();
    }

    public void btnStart_Click(object sender, EventArgs e)
    {
        StartServer();


    }
    private void InitialiseCPUCounter()
    {
        cpuCounter = new PerformanceCounter(
        "Processor",
        "% Processor Time",
        "_Total",
        true
        );
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        cpuLoad = Convert.ToInt32(cpuCounter.NextValue());
        this.txtCPUusage.Text =
 cpuLoad.ToString() +
 "%";
    }
  static  public string GetLocalIP()
    {
        IPHostEntry host;
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        return "127.0.0.1";
    }
}
    }
tshepang
  • 12,111
  • 21
  • 91
  • 136
ayna
  • 77
  • 1
  • 10

1 Answers1

0

I got it. You're inside a static method. You can't access instance fields inside a static member without the reference of the object.

I mean you need something like

myForm.lstIP.items.add("client connected with ip"+curIP); 

But, I suggest you to avoid static and make all the methods instance, then everything will be fine.

Also note that OnClientConnect will be called in worker thread, so you can't update the UI over there. Refer How to update the GUI from another thread in C#? for more info.

Note: Please post what errors you get, and do mention that whether it is a compile time error or runtime Exception. im unable to access XXX, It is not working are not helpful for us to understand the problem. Stack Overflow question checklist


Your complete code will look like:

public partial class Form1 : Form
{
    public int cpuLoad;
    private PerformanceCounter cpuCounter;
    static public string curIP;
    public static string get_localip = GetLocalIP();

    public Form1()
    {
        InitializeComponent();
        InitialiseCPUCounter();
        timer1.Start();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        lblServerIP.Text += " " + get_localip;
    }
    private TcpListener _listener;

    public void StartServer()
    {
        System.Net.IPAddress localIPAddress = System.Net.IPAddress.Parse(get_localip);
        IPEndPoint ipLocal = new IPEndPoint(localIPAddress, 8888);
        _listener = new TcpListener(ipLocal);
        _listener.Start();
        WaitForClientConnect();

    }
    private void WaitForClientConnect()
    {
        object obj = new object();
        _listener.BeginAcceptTcpClient(new System.AsyncCallback(OnClientConnect), obj);
    }
    public void OnClientConnect(IAsyncResult asyn)
    {
        try
        {
            TcpClient clientSocket = default(TcpClient);
            // Socket sck;

            clientSocket = _listener.EndAcceptTcpClient(asyn);
            IPAddress add = IPAddress.Parse(((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString());
            curIP = add.ToString();

            //Use this.Invoke or this.BeginInvoke
            this.Invoke(new Action(() =>
            {
                lstIP.items.add("client connected with ip" + curIP);
                MessageBox.Show("cleint connected with ip:" + curIP);
            }));

            HandleClientRequest clientReq = new HandleClientRequest(clientSocket);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

        WaitForClientConnect();
    }

    public void btnStart_Click(object sender, EventArgs e)
    {
        StartServer();
    }
    private void InitialiseCPUCounter()
    {
        cpuCounter = new PerformanceCounter(
        "Processor",
        "% Processor Time",
        "_Total",
        true
        );
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        cpuLoad = Convert.ToInt32(cpuCounter.NextValue());
        this.txtCPUusage.Text = cpuLoad.ToString() + "%";
    }
    static public string GetLocalIP()
    {
        IPHostEntry host;
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        return "127.0.0.1";
    }
}
Community
  • 1
  • 1
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • i tried it too.My list box remains empty even after instanciating form1.i do not know why. – ayna Aug 08 '14 at 09:54
  • when i made onClientConnect instance,i found access denied for other methods like(waitforclient etc) which are all static – ayna Aug 08 '14 at 10:00
  • @ayna Make that also static. Except `GetLocalIP` method all other has to be instance methods. So obviously `_listener;` field also needs to be instance field. – Sriram Sakthivel Aug 08 '14 at 10:02
  • Updated my answer, Not tested but that should work. If not let me know. btw you need a beginner tutorial on what `static` and instance are how they differ. – Sriram Sakthivel Aug 08 '14 at 10:11