Java SSE method in doGet() not working

131 Views Asked by At

I wrote a method which return an Array converted as String. When calling this method in the main method and printing it out the array is filled. When I am calling the same method in the doGet method for printing it in my html file, the array is empty and it prints only: [] Normally the doGet method schould work because when the method return not the array but just "hello" the html file print the String.

Here ist the code:

public static String test(senderonpremise s){

    String t; 

    //this should be printed
    t =  String.valueOf(s.arrivalList);     
    //startSending();

    //this works in doGet()
    //return "this works";

    // when I return this it works in the main-method but not in DoGet()
    return t;
}


public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/event-stream");
    resp.setCharacterEncoding("UTF-8");

    senderonpremise s = new senderonpremise();
    PrintWriter out = resp.getWriter();

    String next = "data: " + test(s) + "\n\n";
    out.write(next);
    out.flush();

}

/**
  public static void main(String[] args) {
        senderonpremise s = new senderonpremise();
        System.out.print(test(s));
  }
 **/
1

There are 1 best solutions below

0
On

I recommend you using the JEaSSE library: https://github.com/mariomac/jeasse, which is lightweight and works out of the box with Servlets 3.x

@WebServlet(asyncSupported = true)
public class ExampleServlet1 extends HttpServlet {

EventTarget target;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   target = new ServletEventTarget(req).ok().open();
}

public void onGivenEvent(String info) {
   target.send("givenEvent",info);
}
}