Android bufferedReader.readLine持续监听 [英] Android bufferedReader.readLine for continuously listening

查看:95
本文介绍了Android bufferedReader.readLine持续监听的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个连接到服务器的演示应用程序,然后继续监听来自服务器的随机定时输入。发现和连接到服务器的工作正常,现在我启动一个新线程,因此不会阻塞ui。现在,在我的线程中,如果有传入的数据,我需要不断地聆听并做出反应。根据我到目前为止所读的内容,应该这样做:

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
      }
  }

我不了解的内容:readLine()显然只能读取来自服务器的传入数据。因此,一旦服务器停止发送,也就意味着没有任何东西发送时,循环就不会中断吗?

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?

感谢任何想法,
Marcus

Thanx for any thought, Marcus

推荐答案

readLine是一种阻塞方法,因此,如果未收到任何内容,它将在此处等待阻塞执行。循环只会在接收到空值时停止(读取文本文件时,这通常意味着已到达文件末尾)。

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).

尝试在其中检测到关闭的连接另一种方式,或者如果您也对服务器进行编码,请尝试发送诸如 END之类的信息,该信息可以在客户端读取。

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.

这篇关于Android bufferedReader.readLine持续监听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆