开发者

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 += li开发者_开发知识库ne + "\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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜