WebSocketProtocolHandler源碼分析
package io.netty.handler.codec.http.websocketx;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
//WebSocketFrame的子類會進入此類處理
abstract class WebSocketProtocolHandler extends MessageToMessageDecoder<WebSocketFrame> {
//默認true
private final boolean dropPongFrames;
WebSocketProtocolHandler() {
this(true);
}
WebSocketProtocolHandler(boolean dropPongFrames) {
this.dropPongFrames = dropPongFrames;
}
@Override
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
//如果是Ping幀
if (frame instanceof PingWebSocketFrame) {
//ByteBuf引用計數器+1,因爲父類會對frame.content進行釋放。
frame.content().retain();
//寫入Pong幀,在寫入完成後框架對frame.content進行釋放。
ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content()));
return;
}
//如果是Pong幀則不作處理
if (frame instanceof PongWebSocketFrame && dropPongFrames) {
return;
}
//其餘數據幀則先把引用計數器+1,在放入out
//放入out的幀會傳遞到我們自定義的handler處理
out.add(frame.retain());
}
//出現異常繼續傳遞並關閉socket連接
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.fireExceptionCaught(cause);
ctx.close();
}
}