Read from StreamReader doesn't reach the end - Using Telnet protocol

StackOverflow https://stackoverflow.com/questions/22614158

  •  20-06-2023
  •  | 
  •  

سؤال

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?

هل كانت مفيدة؟

المحلول

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().

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top