C# 从TCP客户端获取响应
我创建了这个TCP客户端,但在获取响应时遇到问题。它停在第47行C# 从TCP客户端获取响应,c#,.net,sockets,tcp,tcpclient,C#,.net,Sockets,Tcp,Tcpclient,我创建了这个TCP客户端,但在获取响应时遇到问题。它停在第47行 var line = sr.ReadLine(); 但有时它会将响应放在日志框中,并再次停留在第24行 void log(string x) { richTextBox1.Text += x + Environment.NewLine; } 以下是代码: 如何修复它?您必须首先从TcpClient获取网络流。然后开始读它 使用以下代码 TcpClient tcpClie
var line = sr.ReadLine();
但有时它会将响应放在日志框中,并再次停留在第24行
void log(string x)
{
richTextBox1.Text += x + Environment.NewLine;
}
以下是代码:
如何修复它?您必须首先从TcpClient获取网络流。然后开始读它 使用以下代码
TcpClient tcpClient = new TcpClient ();
// Uses the GetStream public method to return the NetworkStream.
NetworkStream netStream = tcpClient.GetStream ();
if (netStream.CanRead)
{
// Reads NetworkStream into a byte buffer.
byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
// Read can return anything from 0 to numBytesToRead.
// This method blocks until at least one byte is read.
netStream.Read (bytes, 0, (int)tcpClient.ReceiveBufferSize);
// Returns the data received from the host to the console.
string returndata = Encoding.UTF8.GetString (bytes);
Console.WriteLine ("This is what the host returned to you: " + returndata);
}
您想确切地修复什么?它“粘住”在
ReadLine()
,因为该操作会阻塞,直到遇到新行,而新行可能尚未发送或接收。