teuneboon
teuneboon

Reputation: 4064

Receive from socket until specific line in C#

I created this little client socket in C#:

TcpClient socket = new TcpClient(this.ip, this.port);
NetworkStream stream = socket.GetStream();
StreamReader input = new StreamReader(stream);
StreamWriter output = new StreamWriter(stream);

output.WriteLine(request);
output.Flush();

String result = "";
String line = "";
while (line != "GO")
{
    line = input.ReadLine().Trim();
    result += line + "\n";
}

socket.Close();
return result;

It connects just fine, but it stays stuck in the while loop, it will only receive the first line the server socket sends, so the "GO" is never received. Am I doing something wrong here?

Upvotes: 0

Views: 1377

Answers (1)

user153923
user153923

Reputation:

That's probably because it is waiting for data, which will hang your application.

You might need to use a TcpListener instead and call AcceptTcpClient() when receiving data.

Further, I always call this in a thread or BackgroundWorker so that the interface does not hang.

If you need the TcpListerner to stop listening for a TCP connection, then you would call the Stop() method of the instance.

Upvotes: 1

Related Questions