【问题标题】:TCP sockets sr.readline prevents entering data on console?TCP 套接字 sr.readline 阻止在控制台上输入数据?
【发布时间】:2013-05-16 18:01:58
【问题描述】:

您将在下面找到我的代码。问题是,这应该是一个“客户端聊天”程序,因此您可以不断发送消息。但是,不知何故,该应用程序被 console.readline() 阻止,因此提示用户只输入一次消息。有什么解决方法吗?可能正在使用预定义的读取缓冲区?

static void Main(string[] args)
        {
            TcpClient client = new TcpClient("127.0.0.1", 7777);

            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("Message: ");
                    string msg = Console.ReadLine();
                    sw.WriteLine(msg);
                    if (msg == "chao") break;
                    Console.WriteLine(sr.ReadLine());
                }

                s.Close();
            }
            finally
            {
                client.Close();
            }
        }

【问题讨论】:

  • 嗨,服务器代码在这里:pastebin.com/0Jgepy1Z
  • “提示用户只输入一次消息”可能是因为它卡在sr.ReadLine()。它正在等待来自服务器的响应,因为服务器从不发送消息,所以它永远不会出现。尝试将sr.ReadLine() 放入不同的线程。

标签: .net sockets networking tcplistener


【解决方案1】:

sr.readline 阻止在控制台输入数据?

正确。它会一直阻塞,直到从对等端接收到一行。

【讨论】:

    【解决方案2】:

    我知道这不是对您问题的直接回答,但如果您阅读过 Stephen Cleary 的 TCP/IP .Net 套接字常见问题解答,您将获得大量有关使用 .NET 套接字的信息。

    http://blog.stephencleary.com/2009/04/tcpip-net-sockets-faq.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 2011-01-25
      相关资源
      最近更新 更多