从套接字接收直到 C# 中的特定行
我用 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;
它连接得很好,但它停留在 while 循环中,它只会接收服务器套接字发送的第一行,因此永远不会收到“GO”。我在这里做错了什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能是因为它正在等待数据,这会挂起您的应用程序。
您可能需要改用
TcpListener
并在接收数据时调用AcceptTcpClient()
。此外,我总是在线程或BackgroundWorker 中调用它,这样界面就不会挂起。
如果您需要 TcpListerner 停止侦听 TCP 连接,那么您将调用实例的
Stop()
方法。That's probably because it is waiting for data, which will hang your application.
You might need to use a
TcpListener
instead and callAcceptTcpClient()
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.