The server sent events to Android

I have a backend server that sends events to clients as Server Sent Events. I could not find a good library for processing this technology on Android, so I used the backup method of periodically checking the server (via GET for the event endpoint) for new events.

Run by background service every 10 seconds. Needless to say, this is not the best approach. If there are no open source libraries available in this scenario, what is the best approach to memory usage and battery consumption to be periodically checked on the server for new events? Does GET make an API endpoint better or worse than open socket management in Android?

I am open to any suggestions. Thanks.

+6
source share
1 answer

You can simply use HttpUrlConnection to create a permanent connection to the server (Android keep-alive used by default) and treat received messages as streams.

 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(); } 
+1
source

Source: https://habr.com/ru/post/954197/


All Articles