简体   繁体   中英

Java Servlet keep on sending messages

I am using HTML5 server-sent events and I would like to send random messages to the client from the server. Below is some portion of MessageServlet.java :

PrintWriter writer = response.getWriter();
Random rnd1 = new Random();
Random rnd2 = new Random();

for(int i = 0; i < 5; i++) {
    //each message that we end must end with \n\n
    writer.flush();
    System.out.println("This is i : " + i);

    if(i == 4) {
        writer.write("event: close \n");
    }
    if(rnd1.nextInt(100) < 30)
        writer.write("data: "+"{\"Messages\":   [{\"Msg\":\"Success1\"}]}"+"\n\n");  
    else
        writer.write("data: "+"{\"Messages\":   [{\"Msg\":\"Success2\"}]}"+"\n\n");

    try {
        Thread.sleep(rnd2.nextInt(3000)); 
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
writer.close();

It is supposed to stop once the loop reaches 4 however, it is continuously re-sending again the messages. To prove this I printed the counter, i, so as to see if this is true and in fact it prints like this :

THis is i : 0
THis is i : 1
THis is i : 2
THis is i : 3
THis is i : 4
THis is i : 0
THis is i : 1
THis is i : 2
THis is i : 3
THis is i : 4
THis is i : 0
THis is i : 1
THis is i : 2
THis is i : 3
THis is i : 4

Does someone know what I'm doing wrong please? I'm really stuck. Thank you very much.

Server Sent Events-channels are abstracted by keeping a PrintWriter open, that in various ways can be sent to the client when new data arrives there.

To be able to send data to the client, writing to the PrintWriter should likely to be separated from the response logic you have above (to avoid blocking threads that is better to be used to reply to new incoming web requests).

A suggestion would be to keep the PrintWriter channel in a session variable, and have an altogether different service responsible of scheduling and writing out messages, for instance by scheduling an Executor per user/printwriter in a ScheduledExecutorService , that sends some messages and then terminates the the executor, keeping the PrintWriter open until it somehow times out.

I found out that the problem was that I did not close the source event properly. The problem was that the source event was not closing, thus the client was all the time listening again for the same messages. Closing the event source solved the problem! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM