Question

I made this TCP client but I have problems with getting response. It sticks at line 47

var line = sr.ReadLine();

But sometimes it puts response to log box and sticks again at line 24

 void log(string x)
        {
            richTextBox1.Text += x + Environment.NewLine;
        }

Here is code: https://app.box.com/s/7ly47ukztlo5eta3wqbk

How to fix it?

Was it helpful?

Solution

You have to get network stream from TcpClient first. After that start to read it.

Use the following code.

TcpClient tcpClient = new TcpClient ();

// Uses the GetStream public method to return the NetworkStream.
NetworkStream netStream = tcpClient.GetStream ();

if (netStream.CanRead)
    {
        // Reads NetworkStream into a byte buffer. 
        byte[] bytes = new byte[tcpClient.ReceiveBufferSize];

        // Read can return anything from 0 to numBytesToRead.  
        // This method blocks until at least one byte is read.
        netStream.Read (bytes, 0, (int)tcpClient.ReceiveBufferSize);

        // Returns the data received from the host to the console. 
        string returndata = Encoding.UTF8.GetString (bytes);

        Console.WriteLine ("This is what the host returned to you: " + returndata);

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top