Note that there are some explanatory texts on larger screens.

plurals
  1. POSSE and Servlet 3.0
    primarykey
    data
    text
    <p>I have registered a typical SSE when page loads:</p> <p><strong>Client:</strong></p> <pre><code>sseTest: function(){ var source = new EventSource('mySSE'); source.onopen = function(event){ console.log("eventsource opened!"); }; source.onmessage = function(event){ var data = event.data; console.log(data); document.getElementById('sse').innerHTML+=event.data + "&lt;br /&gt;"; }; } </code></pre> <p>My Javascript-Debugger says, that "eventsource opened!" was successfully.</p> <p><strong>My Server Code is a Servlet 3.0:</strong></p> <pre><code>import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns={"/mySSE"}, name = "hello-sse", asyncSupported=true) public class MyServletSSE extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/event-stream"); resp.setCharacterEncoding("UTF-8"); Random random = new Random(); PrintWriter out = resp.getWriter(); //AsyncContext aCtx = req.startAsync(req, resp); //ServletRequest sReq = aCtx.getRequest(); String next = "data: " + String.valueOf(random.nextInt(100) + 1) + "\n\n"; //out.print("retry: 600000\n"); //set the timeout to 10 mins in milliseconds out.write(next); out.flush(); // do not close the stream as EventSource is listening //out.close(); //super.doGet(req, resp); } } </code></pre> <p>The code works! The Client-Code triggers the doGet()-Method every 3 seconds and retrieves the new data.</p> <p><strong>Questions:</strong> However, I wonder <strong>how I can make this code better</strong> by using new Servlet 3.0 Futures such as Async-Support or asyncContext.addListener(asyncListener) or something else which I do not know. As I never closes the stream, I wonder <strong>how my server will scale</strong>?</p> <p>Theoretically, the best approach would be to trigger the doGet()-Method via server-side-code explicitly when new data is there, so the client does not need to trigger the client-side "onmessage()"-Method and therefore the server side "doGet()"-Method every 3 seconds for new data.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload