Эх сурвалжийг харах

优化WebSocketBinaryFrameCodec编解码器

johnclot69 3 долоо хоног өмнө
parent
commit
95ae4539ef

+ 2 - 2
incubator-core/src/main/java/com/incubator/core/network/WebSocketHandshakeHandler.java

@@ -6,7 +6,7 @@ import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelPipeline;
 import io.netty.channel.SimpleChannelInboundHandler;
 import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.HandshakeComplete;
-import com.incubator.core.protocol.BinaryWebSocketFrameCodec;
+import com.incubator.core.protocol.WebSocketBinaryFrameCodec;
 import com.incubator.core.protocol.MsgPackCodec;
 
 /**
@@ -44,7 +44,7 @@ public class WebSocketHandshakeHandler extends SimpleChannelInboundHandler<Objec
     protected void webSocketHandComplete(ChannelHandlerContext ctx) {
         ChannelPipeline pipeline = ctx.pipeline();
         // 添加 WebSocketFrame 到 ByteBuf 的编解码器
-        pipeline.addLast(new BinaryWebSocketFrameCodec());
+        pipeline.addLast(new WebSocketBinaryFrameCodec());
         // 添加 MsgPack 编解码器
         pipeline.addLast(new MsgPackCodec());
         // 添加业务逻辑处理器(例如处理消息转发等)

+ 8 - 4
incubator-core/src/main/java/com/incubator/core/protocol/BinaryWebSocketFrameCodec.java → incubator-core/src/main/java/com/incubator/core/protocol/WebSocketBinaryFrameCodec.java

@@ -13,17 +13,21 @@ import java.util.List;
  * @author johnc
  */
 @ChannelHandler.Sharable
-public class BinaryWebSocketFrameCodec extends MessageToMessageCodec<WebSocketFrame, ByteBuf> {
+public class WebSocketBinaryFrameCodec extends MessageToMessageCodec<WebSocketFrame, ByteBuf> {
 
     @Override
     protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) {
-        out.add(new BinaryWebSocketFrame(msg.retain()));
+        out.add(new BinaryWebSocketFrame(msg.retain())); // 包装为 BinaryWebSocketFrame,并增加引用计数
     }
 
     @Override
     protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) {
-        if (frame instanceof BinaryWebSocketFrame) {
-            out.add(frame.content().retain());
+        if (frame instanceof BinaryWebSocketFrame binaryFrame) {
+            ByteBuf content = binaryFrame.content();
+            out.add(content.retain()); // 引用计数增加,避免内容被释放
+        } else {
+            // 非二进制消息直接丢弃或日志记录
+            ctx.fireExceptionCaught(new IllegalArgumentException("Unsupported WebSocketFrame type: " + frame.getClass().getName()));
         }
     }
 }