Arsalan Qaiser
Arsalan Qaiser

Reputation: 457

C# TCP Client and server having trouble

I was build client and server communication. So I am creating two separate projects. Problem is that this is not working.

Server code:

private void Form1_Load(object sender, EventArgs e)
{
    IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
    int port = 13000;
    TcpListener server = new TcpListener(ipaddress, port);
    server.Start();
    while (true)
    {
        TcpClient client = server.AcceptTcpClient();
        label1.Text = "That Connected to Server";
    }
}

Client code:

private void Form1_Load(object sender, EventArgs e)
{
    IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
    int port = 13000;

    TcpClient obj = new TcpClient(ipaddress.ToString(), port);
    while (true)
    {
        label1.Text = "connected";
    }
}

This code work fine on console application. But not working on windows form. I am running both application but there is no output on the screen. Please help me how to fix it.

Thanks in advance

Upvotes: 0

Views: 136

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67070

Windows application are event driven. If you put a while(true) loop in your Form.Load event then it won't ever exit that function (and you won't ever see any interface). You have to run that code in a separate thread then you'll BeginInvoke results to your UI thread. Something like this:

private void Form1_Load(object sender, EventArgs e)
{
    _thread = new Thread(ListenerThread);
    _thread.IsBackground = true;
    _thread.Start();
}

private Thread _thread;

private void ListenerThread()
{
    IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
    int port = 13000;
    TcpListener server = new TcpListener(ipaddress, port);
    server.Start();
    while (true)
    {
        TcpClient client = server.AcceptTcpClient();
        BeginInvoke(new MethodInvoker(() => label1.Text = "That Connected to Server"));
    }
}

Of course on UI callback method you need to perform something more (be careful with with lambdas and anonymous delegates because of captured variables may be not thread-safe). Do the same for client too and you'll be done.

Upvotes: 3

Related Questions