2011-04-30 61 views
1

我需要从服务器应用程序接收第二个答复。当我第一次连接到服务器应用程序时,我收到了答复。但是当我尝试发送另一条消息时,我无法收到它。使用TcpClient和StreamReader不能接收多条消息

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

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"); 
} 
+0

哪种协议是这样吗? – 2011-04-30 06:16:00

+0

协议?你什么意思?你的意思是发送的消息? – 2011-04-30 06:25:26

+0

是 - 发送和接收的消息的指定格式是什么?它应该是CONNECT \ n登录... \ n密码... \ n \ n \ 0?此外,它是如何失败 - 你是否得到一个错误或没有被打印出来? – 2011-04-30 06:30:13

回答

0

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 
     } 


UPDATE:以下也可工作,在这种情况下,你并不需要担心设置超时或捕获异常:

  while(true) 
     { 
      r = sr.ReadLine(); 
      Console.WriteLine(r); 
      if (sr.Peek() < 0) break; 
     } 
+0

虐待这位先生。生病后会给你一个反馈。谢谢你的解释..我之所以有这样一种协议,是因为它需要一个STOMP。即时连接到它之一..首先,当我尝试连接,然后订阅它回复的消息..然后像我上面发布的代码..当我尝试发送消息(例如即时通讯获取名称列表) ,我的代码只是停止这部分代码... r = sr.ReadLine(); – 2011-04-30 08:27:12