【发布时间】:2017-06-11 09:14:30
【问题描述】:
我正在客户端和服务器之间创建非常简单的 TCP/IP 通信程序。目的只是在它们之间交换一些字符串。
Client Server 端需要向Server 发送和接收一些简单的字符串。
问题是当我使用 StreamWriter 将数据发送到 Sever 时它工作得很好。但是,当我启用 StreamReader 时,while 循环将永远挂起。 "Console.Write(">");"行仅在开始时执行一次,但第二次不再提示。
这是下面的代码。
注意“_client”已经连接了 TcpClient 的套接字,在另一部分代码中声明为 TcpClient _client。
_sReader = new StreamReader(_client.GetStream(), Encoding.ASCII);
_sWriter = new StreamWriter(_client.GetStream(), Encoding.ASCII);
_isConnected = true;
String sData = null;
while (_isConnected)
{
Console.Write("> ");
sData = Console.ReadLine();
_sWriter.WriteLine(sData);
_sWriter.Flush();
//If I commnet out these two lines of code below, then there is no problem. Program works fine.
String sDataIncomming = _sReader.ReadLine();
Console.WriteLine(sDataIncomming);
//While loop just hanging after this line.
//It does not even break the while loop.
//Either while loop goes back to the top of the line.
//Just stuck here. Why ?
}
如果我将 StreamReader 的两行代码注释掉,程序又可以完美运行了。
我该如何解决这个问题?非常感谢分享您的知识。
亲切的问候。
【问题讨论】:
标签: c# .net server client tcp-ip