返回的答案太长,但是我一直等到看到Thread.Sleep()多少。我该怎么做才能看到它们?而不是Thread.Sleep(100)
if (NetworkInterface.GetIsNetworkAvailable())
{
TcpClient tcpCli = new TcpClient();
bool connectionStatus = GetConnection(ipAddress, tcpPort, out tcpCli);
NetworkStream stream = null;
if (connectionStatus == false)
return "Could not establish TCP connection";
else
{
try
{
//Send data to TCP Client
Byte[] data = Encoding.ASCII.GetBytes(SendData);
stream = tcpCli.GetStream();
stream.Write(data, 0, data.Length);
//Thread.Sleep(100);
//Read data from TCP Client
data = new Byte[tcpCli.ReceiveBufferSize];
Int32 bytes = stream.Read(data, 0, data.Length);
string answer = Encoding.ASCII.GetString(data, 0, bytes);
if (answer.Contains("**"))
return answer;
else
return "Panel no answer";
}
catch (Exception) { return "COMMUNICATION ERROR"; }
finally { tcpCli.Close(); }
}
}
答案 0 :(得分:0)
我以这种方式解决了。也许可以帮助某人。
public static string TcpPanelGetSet(string ipAddress, int tcpPort, string SendData, string finishValue)
{
if (NetworkInterface.GetIsNetworkAvailable())
{
TcpClient tcpCli = new TcpClient();
bool connectionStatus = GetConnection(ipAddress, tcpPort, out tcpCli);
NetworkStream stream = null;
if (connectionStatus == false)
return "Could not establish TCP connection";
else
{
try
{
//Send data to TCP Client
Byte[] data = Encoding.ASCII.GetBytes(SendData);
stream = tcpCli.GetStream();
stream.Write(data, 0, data.Length);
//Read from TCP Client
string answer = "";
DateTime st = DateTime.Now;
DateTime et = DateTime.Now.AddSeconds(300);
do
{
st = DateTime.Now;
if (st > et)
return "TIME-OUT";
data = new Byte[tcpCli.ReceiveBufferSize];
Int32 bytes = stream.Read(data, 0, data.Length);
string tmpAnswer = Encoding.ASCII.GetString(data, 0, bytes);
if (tmpAnswer.Contains(finishValue))
{
answer += tmpAnswer;
break;
}
answer += tmpAnswer;
} while (et > st);
if (answer.Contains("**"))
return answer;
else
return "Panel no answer";
}
catch (Exception) { return "COMMUNICATION ERROR"; }
finally { tcpCli.Close(); }
}
}
else
{
return "THERE IS NO CONNECTION";
}
}