gpt4 book ai didi

android - 服务器在 Android 中发送事件

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:17:03 25 4
gpt4 key购买 nike

我有一个后端服务器将事件作为服务器发送事件发送给客户端。我一直无法在 Android 上找到一个很好的库来处理这项技术,所以我一直在使用后备方法定期检查服务器(通过 GET 到事件端点)是否有新事件。

这是由后台服务每 10 秒完成一次。不用说,这不是最好的方法。如果没有任何开源库可用于此场景,那么在内存使用和电池消耗方面定期检查服务器后端是否有新事件的最佳方法是什么?与在 Android 中管理开放套接字相比,对 API 端点执行 GET 操作是好是坏?

我愿意接受任何建议。谢谢。

最佳答案

您可以简单地使用 HttpUrlConnection 与服务器建立持久连接(Android 默认使用 keep-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();
}

关于android - 服务器在 Android 中发送事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18903760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com