Anand Anand - 2 months ago 23
AngularJS Question

How to create Event-source server using Spring boot?

How to create event-source server using spring boot application?
From the below link, I don't see Java-spring boot example.
Any reference would help.

http://www.html5rocks.com/en/tutorials/eventsource/basics/

Answer

This is a simple implementation with Spring 4.2. Don't take into account the Thread, it's there only for demo purposes:

@RestController
public class AccountsRestController {

    @RequestMapping("/accounts/alerts")
    public SseEmitter getAccountAlertsNoPathVariable(HttpSession session) {

        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);

        Thread t1 = new Thread(() ->{
            try {
                int i = 0;
                // Send 10000 messages
                while(++i<=10000){
                    Thread.sleep(1000);
                    System.out.println("Sending");
                    try{
                        emitter.send(new Alert((long)i, "Alert message"+i));
                    }catch(ClientAbortException cae){
                        //The client is not there anymore, we get out of the loop
                        i = 10000;
                    }
                }
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();

        return emitter;
    }
Comments