SSE / EventSource:如何区分超时和其他角度错误

时间:2019-02-04 11:15:39

标签: angular timeout server-sent-events eventsource

我正在使用SSE将通知从Spring Boot服务器发送到angular客户。每隔10分钟我的SseEmitter超时(出于安全原因)。但是,由于所有错误和超时都是在eventSource.onError事件侦听器中接收的,因此我无法区分此超时和其他错误。 是否可以在客户端中区分错误和超时?。下面是我的代码:

P.S。这就是我用于EventSource https://www.npmjs.com/package/event-source-polyfill

的方式

角度事件源:

const eventSource = new EventSourcePolyfill(AppUrl.NEW_NOTIFICATIONS, { headers: { Authorization: 'Bearer ' + this._authService.getAccessToken() } });
    eventSource.onmessage = (message) => {
      console.log('message received');
    };

    eventSource.onopen = (a) => {
      console.log('Connection Open');
    };

    eventSource.onerror = (e) => {
      eventSource.close();
      console.log('Connection closed');
    };
    eventSource.addEventListener('heartBeat', message => {
      console.log('keepalive message');
    });

我的控制器代码是:

@RequestMapping(value = "/notifications", method = RequestMethod.GET)
    public ResponseEntity<SseEmitter> streamNotification(
            @RequestParam("id") String id) {
        final SseEmitter emitter = new SseEmitter(600000L);
        service.addEventToStore(credentialProvider.getUserId(), id, emitter);
        return ResponseEntity.ok()
                .headers(responseHeaders).body(emitter);
    }

我需要在超时时执行某些操作,并在发生其他任何错误时关闭连接。我该如何实现?

0 个答案:

没有答案