Websocket: Closing browser triggers onError() in c

2020-02-12 12:23发布

问题:

When you close your browser while you have an active websocket connection, the following behavior seems to depend on the browser:

  • Firefox: Triggers onClose().
  • Internet Explorer: Triggers onClose().
  • Chrome: Will trigger onErr(), the throwable doesn't seem to include a CloseReason.

    01:22:47,428 ERROR [stderr] (default task-5) java.nio.channels.ClosedChannelException 01:22:47,429 ERROR [stderr] (default task-5) at io.undertow.server.protocol.framed.AbstractFramedChannel.receive(AbstractFramedChannel.java:253) 01:22:47,429 ERROR [stderr] (default task-5) at io.undertow.websockets.core.AbstractReceiveListener.handleEvent(AbstractReceiveListener.java:20) 01:22:47,429 ERROR [stderr] (default task-5) at io.undertow.websockets.core.AbstractReceiveListener.handleEvent(AbstractReceiveListener.java:15) 01:22:47,429 ERROR [stderr] (default task-5) at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92) 01:22:47,429 ERROR [stderr] (default task-5) at io.undertow.server.protocol.framed.AbstractFramedChannel$FrameReadListener.handleEvent(AbstractFramedChannel.java:615) 01:22:47,429 ERROR [stderr] (default task-5) at io.undertow.server.protocol.framed.AbstractFramedChannel$FrameReadListener.handleEvent(AbstractFramedChannel.java:601) 01:22:47,429 ERROR [stderr] (default task-5) at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92) 01:22:47,429 ERROR [stderr] (default task-5) at org.xnio.conduits.ReadReadyHandler$ChannelListenerHandler.readReady(ReadReadyHandler.java:66) 01:22:47,429 ERROR [stderr] (default task-5) at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:87) 01:22:47,430 ERROR [stderr] (default task-5) at org.xnio.nio.WorkerThread.run(WorkerThread.java:531)

I tried to make a workaround, catching the onbeforeunload event....

window.onbeforeunload = function () {
            console.log("closing window");
            return null;
        }

...but it looks like, this is not possible with current versions of Chrome.

Why does Chrome trigger onError(), instead of closing the connection? I don't think it's an error, when a user is closing the browser window. Mostly there is no more need for the webservice, so the user will close the window.

Also, see this thread: Should WebSocket.onclose be triggered by user navigation or refresh?

I have to call OnClose() if onError() is triggered, because I can't close the connection when a Chrome user closes the window.

@OnError
    public void onErr(Throwable t) {
        onClose(this.container.getWsSession(), null);

    }

I'm not sure if every event, that triggers onError() should close the connection....