I am having a TCP server, which will listen to a port for a input query, executes it and gives the output. I need to create a TCPClient application which will connect to the port, send the query, read the output and disconnects from the port.
Implementation of client:
private string SendMessage(string host, int port, string message)
{
TcpClient client = new TcpClient(host, port);
NetworkStream stream = client.GetStream();
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);
while (!stream.DataAvailable) for (int i = 0; i < 1000; i++) ;
StringBuilder sb = new StringBuilder();
while (stream.DataAvailable)
{
data = new byte[client.ReceiveBufferSize];
stream.Read(data, 0, data.Length);
sb.Append(Encoding.UTF8.GetString(data));
}
return sb.ToString();
}
Problem: The server is taking a small time lag for processing the query and writing the data to the port. Also there is no way to identify the endpoint of the result. Sometimes my client application is not able to read the data completely (the data may be written much slower than the reading, or there is a pause while writing the outputs of the query)
Constraints:
1. The server is a third party product and we can't change the way it operates.
2. We should not use Thread.Sleep in the client application as it degrades the performance.
3. We should not read one byte at a time from the port as it degrades the performance.
Please give me any idea for reading the data completely. Is there any way to write a client class, which reads the data asynchronously?
Any pointers to other articles are welcome.