1

我正在尝试使用端口 2628 连接到 dict.org 服务器,但无法从服务器获得完整响应。代码如下所示:

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();
            }

当我为这个词输入“hello”时,它只会得到 1 行响应,然后如果我输入任何内容并按 enter,它将显示下一行,依此类推。如何一次显示完整的响应?

4

1 回答 1

1

这就是我想出的:

        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();
        }
    }

您还需要解决其他响应类型。当没有找到任何单词时,我的解决方案会挂起,但这可以通过注意特定的响应类型数字而不是点字符来轻松解决。

快乐编码!

编辑:这绝不是一个优雅的解决方案,我只是想说明原理。

于 2012-11-25T15:17:28.583 回答