Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSE Emitter : Manage timeouts and complete()

I am writing a web app where multiple listeners(Evcentsource SSE clients JS) will be connected to my server . what i want to do is

  1. Store SSE emitter per connected listener : can be done in memory or any other means by assigning id to each client I am able to achieve this so far
  2. Now the question ; How do i send a response/event to specific client connected to my web app ? while doing this SSEEmmiters stored are either getting completed or timed out. how do i prevent this ? how do i keep sseEmmiter available open for infinite time (till client closes) and send events selectively .
like image 706
aditya mujumdar Avatar asked Dec 10 '22 14:12

aditya mujumdar


1 Answers

If you want the sseEmmiter available open for infinite time, you can simply set the time out to -1L

and to send events selectively put all of sseEmmiters in a map with specific key to use it when you want to send event like i did in this code .

@Controller
@RequestMapping(path = "api/person")
public class PersonController {

 @Autowired
 private PersonRepository personRepository;
 private Map<String, SseEmitter> onPersonAddedSseEmitters = new ConcurrentHashMap<>();

 @PostMapping(path = "/add")
 public @ResponseBody
 String addPerson(@RequestBody Person person) {
   person.setId(new Random().nextLong());
   personRepository.save(person);
   onPersonAddedSseEmitters.forEach((key, sseEmitter) -> {
     try {
       if (person.getName().startsWith(key.split("-")[0])) {
         sseEmitter.send(person);
       }
     } catch (Exception ignored) {
       sseEmitter.complete();
       onPersonAddedSseEmitters.remove(key);
     }
   });
   return "Saved";
 }

 @GetMapping(path = "/onPersonAdded/{prefix}")
 public SseEmitter onPersonAdded(@PathVariable String prefix) {
   SseEmitter sseEmitter = new SseEmitter(-1L);
   onPersonAddedSseEmitters.put(prefix + "-" + new Random().nextLong(), sseEmitter);
   return sseEmitter;
 }
}
like image 167
Falah H. Abbas Avatar answered Dec 24 '22 10:12

Falah H. Abbas