Question

I am using Telnet protocol in order to query UNIX servers and get the output of some commands. I am using the Minimalistic telnet from code project and I did a slight modification to enable reading output to the end of the stream:

public void WriteCommand(string cmd)
{
    using (NetworkStream stream = tcpSocket.GetStream())
    {
        using (StreamWriter writer = new StreamWriter(stream))
        {
            writer.AutoFlush = true;

            using (StreamReader reader = new StreamReader(stream))
            {
                 string message = cmd;
                 writer.WriteLine(message);
                 writer.Flush();

                 while (!reader.EndOfStream)
                 {
                     string response = reader.ReadLine();
                     Console.WriteLine(response);
                 }
             }
         }
     }
 }

The problem is that when I run this method, which is supposed to return the output till the end, it's blocked because it is not recognizing the end of stream, so the condition reader.EndOfStream() is never reached.

Can you tell me what's the problem with my code please?

Was it helpful?

Solution

As @itsme86 wrote the connection remains open. Do you expect any response from the commands being send? If true then read the response, parse it, find some delimiter or other finish symbol which will mark that command has been executed successfully and break you while().

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