Is there a way to be notified when a client has unsubscribe from server sent events?

时间:2016-04-21 22:32:33

标签: http express httprequest server-sent-events

As I understand when a request to an event emitter on the server arrives, that request is never closed and you only need to res.write() every time you would like to send a message. However is there a way to be notified when the client that performed this request has left? Is there a property on the request object?

suppose I have the following route

app.get('/event',function(req,res){

//set response headers

//how do I check if req object is still active to send a message and perform other actions?

})

1 个答案:

答案 0 :(得分:0)

事件的基本顺序在其他框架中应该类似,但这个例子是Grails 3.3。

首先设置要订阅的端点,然后关闭连接。

def index() {
    // handler for GET /api/subscribe

    rx.stream { Observer observer ->

        // This is the Grails event bus. background tasks,
        // services and other controllers can post these
        // events, CLIENT_HANGUP, SEND_MSG, which are
        // just string constants.

        eventBus.subscribe(CLIENT_HANGUP) {String msg ->

            // Code to handle when the grails event bus
            // posts CLIENT_HANGUP
            // Do any side effects here, like update your counter
            // Close the SSE connection

            observer.onCompleted()
            return
        }

        eventBus.subscribe(SEND_MSG) {String msg ->

            // Send a Server Sent Event

            observer.onNext(rx.respond(msg))
        }
    }
}



def disconnecting()
{
    // handler for GET /api/disconnect
    // Post the CLIENT_HANGUP event to the Grails event bus

    notify(CLIENT_HANGUP, 'disconnect')
}

现在在客户端,只要您的用例需要,就需要安排GET /api/disconnect。假设您想要注意某人离开您的页面时,您可以在window.onbeforeunload上注册一个功能。此示例使用Vue.jsAxios

  window.onbeforeunload = function (e) {
    e.preventDefault()
    Vue.$http({
      method: 'get',
      url: 'http://localhost:8080/api/disconnect'
    })
      .then((response) => { console.log(response) })
      .catch(({error}) => { console.log(error) })
  }

对于像Grails这样的Servlet堆栈,我发现我需要这样做,即使我在浏览器消失时没有自己做家务。没有它,页面重新加载会导致后端出现IOExceptions。