Returning answer is too long, but I wait until I see how much my Thread.Sleep(). What should I do to see them all? instead of 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(); }
}
}
I solved it that way. maybe it could help someone.
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";
}
}