Android bufferedReader.readLine for continuously listening

早过忘川 提交于 2020-02-23 04:14:57

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/11359650/android-bufferedreader-readline-for-continuously-listening

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!