Hen*_*que 7 android android-networking server-sent-events
我有一个后端服务器,它将事件作为服务器发送事件发送给客户端.我在Android上找不到用于处理这项技术的好库,所以我一直在使用一种回退方法来定期检查服务器(通过GET到事件端点)以获取新事件.
这是通过后台服务每10秒完成的.不用说,这不是最好的方法.如果没有任何开源库可用于此方案,那么在内存使用和电池消耗方面,定期检查服务器后端是否有新事件的最佳方法是什么?是否比在Android中管理开放套接字更好或更差地对API端点进行GET?
我愿意接受任何建议.谢谢.
您可以简单地使用HttpUrlConnection与服务器建立持久连接(Androidkeep-alive默认使用)并将收到的消息视为流。
public class HttpRequest extends AsyncTask {
@Override
protected Object doInBackground(Object[] params){
try {
URL url = new URL("http://simpl.info/eventsource/index.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
Log.d("SSE", "http response: " + urlConnection.getResponseCode());
//Object inputStream = urlConnection.getContent();
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
Log.d("SSE reading stream", readStrem(inputStream)+"");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("SSE activity", "Error on url openConnection: "+e.getMessage());
e.printStackTrace();
}
return null;
}
}
private String readStrem(InputStream inputStream) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try{
reader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while((line = reader.readLine()) != null){
Log.d("ServerSentEvents", "SSE event: "+line);
}
}catch (IOException e){
e.printStackTrace();
}finally {
if(reader != null){
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return response.toString();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3139 次 |
| 最近记录: |