我正在尝试使用端口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键,它将显示下一行,依此类推。如何立即显示完整的回复?
答案 0 :(得分: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();
}
}
您还需要解决其他响应类型。当没有找到任何单词时,我的解决方案会挂起,但通过观察特定的响应类型数而不是点字符,可以很容易地解决这个问题。
快乐的编码!
编辑:这绝不是一个优雅的解决方案,我只是想说明这个原则。