C# 程序开始时延迟3分钟为什么?C语言中的socket编程
在下面的程序开始时,我将获得3分钟的延迟。但在超级终端中,它每2秒显示一次数据 她是我下面的代码。请让我知道我哪里出错了。我如何纠正这个延迟。有什么建议吗C# 程序开始时延迟3分钟为什么?C语言中的socket编程,c#,sockets,timedelay,C#,Sockets,Timedelay,在下面的程序开始时,我将获得3分钟的延迟。但在超级终端中,它每2秒显示一次数据 她是我下面的代码。请让我知道我哪里出错了。我如何纠正这个延迟。有什么建议吗 private void StartReceiving() { // coding part of receiving changed. try { string IPStr = textBox1_IPaddress.Text.Trim(); string portStr = textB
private void StartReceiving()
{
// coding part of receiving changed.
try
{
string IPStr = textBox1_IPaddress.Text.Trim();
string portStr = textBox2_Port.Text.Trim();
int port = Convert.ToInt32(portStr);
int bytesRead = 0;
byte[] buffer = new byte[9];
//------------------------------------------------------------------
IPAddress ipAddress = System.Net.IPAddress.Parse(IPStr);
//create server's tcp listener for incoming connection
try
{
textBox3.Visible = true;
client = new TcpClient();
client.Connect(IPStr, port);
ns = client.GetStream();
while (true)
{
if (ns.DataAvailable)
{
byte[] data = ReadNumberBytes(ns, 9);
ASCIIEncoding encoder = new ASCIIEncoding();
msg = encoder.GetString(data);
textBox3.AppendText(msg);
textBox3.AppendText("\n");
GetData(msg);
}
else
{
Thread.Sleep(4000);
byte[] data = ReadNumberBytes(ns, 9);
ASCIIEncoding encoder = new ASCIIEncoding();
msg = encoder.GetString(data);
GetData(msg);
}
}
client.Close();
}
catch (SocketException se)
{
//message box;
}
}
}
public static byte[] ReadNumberBytes(NetworkStream stream, int n)
{
byte[] buffer = new byte[n];
int bytesRead = 0;
int chunk;
while (bytesRead < n)
{
chunk = stream.Read(buffer, (int)bytesRead, buffer.Length - int)bytesRead);
if (chunk == 0)
{
// error out.
throw new Exception("Unexpected disconnect");
}
bytesRead += chunk;
}
return buffer;
}
您是否得到SocketException或任何异常?此方法是否在其自己的线程上?我猜不是因为你直接访问TextBoxes。在我看来这需要很长时间,因为如果数据不可用,你在那里有4秒钟的睡眠时间。我真的不明白你为什么这么做,但我怀疑你会发现,如果你摆脱这种睡眠,速度会快得多。使用textbox查看是否接收到数据。当附加到textbox本身时,它会给它带来很大的延迟。@Jim Mischel:我在数据不可用时增加了4秒延迟,因为我的一个设备有时每隔4秒提供数据。因此增加了4秒延迟