【问题标题】:Can't receive more than one message using TcpClient and StreamReader使用 TcpClient 和 StreamReader 无法接收多于一条消息
【发布时间】:2011-04-30 15:21:55
【问题描述】:

我需要接收来自服务器应用程序的第二个回复。当我第一次连接到服务器应用程序时,我得到了回复。但是当我尝试发送另一条消息时,我收不到它。

我已尝试寻找解决方案,但找不到任何东西。我相信问题是我的读者的指针仍然在最后。这就是为什么我无法阅读下一个回复的原因。这是我的代码:

public static void XConn()
{
    TcpClient client = new TcpClient();
    client.Connect("xxx.xxx.xxx.xxx",xx); // i cant show the IP sorry
    Stream s = client.GetStream();
    StreamReader sr = new StreamReader(s);
    StreamWriter sw = new StreamWriter(s);

    String r = "";
    sw.AutoFlush = true;      

    sw.WriteLine("CONNECT\nlogin:xxxxxxx \npasscode:xxxxxxx \n\n" + Convert.ToChar(0)); // cant show also

    while(sr.Peek() >= 0)
    {
        r = sr.ReadLine();
        Console.WriteLine(r);
        Debug.WriteLine(r);
        if (r.ToString() == "")
            break;
    }

    sr.DiscardBufferedData();

    //get data needed, sendMsg is a string containing the message i want to send
    GetmsgType("1");
    sw.WriteLine(sendMsg);

    // here i try to receive again the 2nd message but it fails =(
    while(sr.Peek() >= 0)
    {
        r = sr.ReadLine();
        Console.WriteLine(r);
        Debug.WriteLine(r);
        if (r.ToString() == "")
            break;
    }

    s.Close();

    Console.WriteLine("ok");
}

【问题讨论】:

  • 协议?你是什​​么意思?您是指发送的消息吗?
  • 是——发送和接收的消息的指定格式是什么?它应该是 CONNECT\nlogin...\npassword...\n\n\0 吗?另外,它是如何失败的——你是遇到错误还是没有打印出来?

标签: c# tcpclient streamreader


【解决方案1】:

TcpClient.GetStream() 返回一个NetworkStream,它不支持查找,因此您无法更改阅读器指针,并且只要连接打开,它也永远不会真正结束。这意味着当服务器在响应之间存在延迟时,StreamReader.Peek() 方法可能会返回误导性的 -1

获得响应的一种可靠方法是设置读取超时并一直循环直到抛出异常,您可以捕获并继续执行。该流仍可用于发送另一条消息。

       s.ReadTimeout = 1000;

       try
       {
          sw.WriteLine(sendMsg);

          while(true)
          {
            r = sr.ReadLine();
            Console.WriteLine(r);
          } 

         sr.DiscardBufferedData(); 
       }
      catch(IOException)
       {
         //Timed out—probably no more to read
       }


更新:以下也可能有效,在这种情况下,您不必担心设置超时或捕获异常:
         while(true)
         {
           r = sr.ReadLine();
           Console.WriteLine(r);
           if (sr.Peek() < 0) break;
         } 

【讨论】:

  • 我试试这个先生。稍后我会给你反馈。谢谢你的解释.. 我有这种协议的原因是因为它需要 STOMP。我正在连接其中一个..起初当我尝试连接然后订阅它回复是一条消息..然后就像我在上面发布的代码..当我尝试发送消息时(例如我得到一个名字列表) ,我的代码只是停止这部分代码... r = sr.ReadLine();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-02
  • 2022-01-12
相关资源
最近更新 更多