Question

Anyway I'm trying to make a Client connect to a Server using TCPListener and TCPClient whenever i have the while (true) code, it freezes my whole application.

My code:

private void addSocket(int port)
{
    server = new TcpListener(IPAddress.Any, port);
    server.Start();
    client = server.AcceptTcpClient();
    sr = new StreamReader(client.GetStream());
    sw = new StreamWriter(client.GetStream());
    toolStripStatusLabel2.Text = "waiting for connection";
    while (true)
    {
        toolStripStatusLabel2.Text = "client connected";
    }
    server.Stop();
    client.Close();
}
Was it helpful?

Solution

while(true) is an infinite loop, the only way of getting out of it is using break. Or changing while(true) to some condition that alternatively ends.

In this code, the while(true) part makes no real sense to me, you should probably add something else to that part as well, e.g. some connection stuff etc.

OTHER TIPS

That is because the while (true) never end. Add a condition that will return false at some point.

In this case the while doesn't make sense to me. What is your intent with it? Just start a Task or BackgroundWorker to process the stream.

Perhaps your program will run ok if you just delete while statement because i don't see any need of it in your code

You don't need it to be All the time , do you?

  private void addSocket(int port)
{
server = new TcpListener(IPAddress.Any, port);
server.Start();
client = server.AcceptTcpClient();
sr = new StreamReader(client.GetStream());
sw = new StreamWriter(client.GetStream());
toolStripStatusLabel2.Text = "waiting for connection";


    toolStripStatusLabel2.Text = "client connected";

server.Stop();
client.Close();
toolStripStatusLabel2.Text = "client not connected";
}

You just change a text for it. Then you could change it later!!.

Next time if you want to use while (true){}; consider using Thread

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top