c# - Can't receive more than one message using TcpClient and StreamReader -


i need receive second reply server application. when connect server app first time reply. when try send message, can't receive it.

i've tried searching solution can't find anything. believe problem pointer on reader still @ end. that's why can't read next reply. here code:

public static void xconn() {     tcpclient client = new tcpclient();     client.connect("xxx.xxx.xxx.xxx",xx); // cant show 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      while(sr.peek() >= 0)     {         r = sr.readline();         console.writeline(r);         debug.writeline(r);         if (r.tostring() == "")             break;     }      sr.discardbuffereddata();      //get data needed, sendmsg string containing message want send     getmsgtype("1");     sw.writeline(sendmsg);      // here try receive again 2nd message fails =(     while(sr.peek() >= 0)     {         r = sr.readline();         console.writeline(r);         debug.writeline(r);         if (r.tostring() == "")             break;     }      s.close();      console.writeline("ok"); } 

tcpclient.getstream() returns networkstream, doesn't support seeking can't change reader pointer, , long connection open, it's never @ end, either. means streamreader.peek() method might returning misleading -1 when there delay server between responses.

one reliable way response set read timeout , keep looping until exception thrown, can catch , carry on. stream still available send message.

       s.readtimeout = 1000;         try        {           sw.writeline(sendmsg);            while(true)           {             r = sr.readline();             console.writeline(r);           }            sr.discardbuffereddata();         }       catch(ioexception)        {          //timed out—probably no more read        } 


update: following may work, in case don't need worry setting timeouts or catching exceptions:

         while(true)          {            r = sr.readline();            console.writeline(r);            if (sr.peek() < 0) break;          }  

Comments