Click here to Skip to main content
15,942,328 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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();
    // Send the message
    byte[] data = Encoding.UTF8.GetBytes(message);
    stream.Write(data, 0, data.Length);
    // Mock thread.sleep
    while (!stream.DataAvailable) for (int i = 0; i < 1000; i++) ;
    // Read the data from the server
    StringBuilder sb = new StringBuilder();
    while (stream.DataAvailable)
        data = new byte[client.ReceiveBufferSize];
        stream.Read(data, 0, data.Length);

    // Return the output
    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)

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.

1 solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900