【问题标题】:while loop hang forever during TCP/IP communication for Client Side?在客户端的 TCP/IP 通信期间,while 循环永远挂起?
【发布时间】: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


    【解决方案1】:

    我想我已经找到了这个问题的部分答案。

    我认为如果套接字没有从服务器接收到任何东西,似乎这条代码行永远卡住了。

    String sDataIncomming = _sReader.ReadLine();
    

    所以新的问题是如何检查某个字符串是否来自服务器?

    如果没有来自服务器的字符串,则停止从套接字侦听。

    【讨论】:

      猜你喜欢
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 2014-05-10
      • 2019-04-05
      相关资源
      最近更新 更多