简体   繁体   中英

Android bufferedReader.readLine for continuously listening

I'm trying to write a demo-app that connects to a server and then simply keeps listening for randomly timed input from the server. Discovering the and connecting to the server works fine, now I start a new thread, so I don't block the ui. Now, in my thread, I need to continuously listen and react if there's incoming data. According to what I've read so far, it should be done like that:

  while (connected) {
      while ((line = bufferedReader.readLine()) != null) {
          // do something with line and contact the ui
      }
  }

What I don't understand: readLine() obviously can only read a line if there's incoming data from the server. So, shouldn't the loop break once the server has stopped sending, meaning when there's nothing sent?

Thanx for any thought, Marcus

readLine is a blocking method, so if nothing is being received, it will wait blocking execution right there. Loop will only stop when a null value is received (when reading a text file this tipically means that the end of file has been reached).

Try to detect closed connections in a different way, or if you also code the server, try sending something like "END", which can be read at the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM