Netty:正确关闭WebSockets

Den*_*nis 5 websocket netty

如何正确关闭服务器端的WebSocket通道/连接?如果我使用a ctx.getChannel().close(),onerror则抛出Brwoser(Firefox 9):

页面加载时,与ws:// localhost:8080/websocket的连接中断

我还尝试CloseWebSocketFrame在以下channelClosed方法中发送WebSocketServerHandler:

public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
        throws Exception {
    CloseWebSocketFrame close = new CloseWebSocketFrame();
    ctx.getChannel().write(close);
}
Run Code Online (Sandbox Code Playgroud)

抛出一个ClosedChannelException(可能与相关?).

tru*_*tin 5

你必须这样做:

ch.write(new CloseWebSocketFrame());
Run Code Online (Sandbox Code Playgroud)

然后服务器将关闭连接.如果连接没有尽快关闭,您可以打电话ch.close().

  • 由于最后的行为,我引入了一个`ChannelClosing`类.我在通道上写了一个这样的实例:`ch.write(new ChannelClosing());`.如果我在我的解码器中找到它(它将我的应用程序数据转换为WebSockets),我将切换到`CloseWebSocketFrame`.有用. (2认同)