Cobold
Cobold

Reputation: 2613

Can't get full response from TCP server

I'm trying to connect to the dict.org server with port 2628 and I can't get the full response from the server. Here is what the code looks like:

TcpClient client = new TcpClient("216.18.20.172", 2628);
            try
            {
                Stream s = client.GetStream();
                StreamReader sr = new StreamReader(s);
                StreamWriter sw = new StreamWriter(s);
                sw.AutoFlush = true;
                Console.WriteLine(sr.ReadLine());
                while (true)
                {
                    Console.Write("Word: ");
                    string msg = Console.ReadLine();
                    sw.WriteLine("D wn {0}", msg);
                    if (msg == "") break;

                    Console.WriteLine(sr.ReadLine());
                }
                s.Close();
            }
            finally
            {
                client.Close();
                Console.ReadLine();
            }

When I enter "hello" for the word, it just gets 1 line of response, then if I enter anything and press enter it would show the next line and so on. How to show the full response at once?

Upvotes: 1

Views: 677

Answers (1)

Jan Kratochvil
Jan Kratochvil

Reputation: 2327

This is what I came up with:

        static void Main(string[] args)
    {
        TcpClient client = new TcpClient("216.18.20.172", 2628);
        try
        {
            Stream s = client.GetStream();
            StreamReader sr = new StreamReader(s);
            StreamWriter sw = new StreamWriter(s);
            sw.AutoFlush = true;
            Console.WriteLine(sr.ReadLine());
            while (true)
            {
                Console.Write("Word: ");
                string msg = Console.ReadLine();
                sw.WriteLine("D wn {0}", msg);
                if (msg == "") break;

                var line = sr.ReadLine();
                while (line != ".") // The dot character is used as an indication that no more words are found
                {
                    Console.WriteLine(line);
                    line = sr.ReadLine();
                }
                sr.ReadLine();
            }
            s.Close();
        }
        finally
        {
            client.Close();
            Console.ReadLine();
        }
    }

You also need to solve for other response types. My solution hangs when no words are found, but that can be easily remedied by watching out for specific response type numbers instead of the dot character.

Happy Coding!

EDIT: This is by no means an elegant solution, I just wanted to illustrate the principle.

Upvotes: 1

Related Questions