目录
1 netty 数据压缩推送
1 入参 获取二进制数据
2 出参 二进制流输出(如果要压缩,查看下文,java Gzip压缩再转化成二进制流,注意和前台交互的编码问题)
1 netty 数据压缩推送
netty数据传送方式分别有
TextWebSocketFrame ---> 文本形式推送
BinaryWebSocketFrame --> 二进制流形式推送
................
1 入参 获取二进制数据
public String binary(ChannelHandlerContext ctx, WebSocketFrame frame){System.out.println("The WebSocketFrame is BinaryWebSocketFrame");BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) frame;byte[] by = new byte[frame.content().readableBytes()];binaryWebSocketFrame.content().readBytes(by);ByteBuf buf = Unpooled.buffer();buf.writeBytes(by);String str = "";if(buf.hasArray()) { // 处理堆缓冲区str = new String(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());} else { // 处理直接缓冲区以及复合缓冲区byte[] bytes = new byte[buf.readableBytes()];buf.getBytes(buf.readerIndex(), bytes);str = new String(bytes, 0, buf.readableBytes());}return str;}
2 出参 二进制流输出(如果要压缩,查看下文,java Gzip压缩再转化成二进制流,注意和前台交互的编码问题)
把 new TextWebSocketFrame(msg) --> new BinaryWebSocketFrame(msg) 就转成二进制流
//用压缩二进制流的方式写 channel 写入消息public static void writeMsgByBinary(ChannelGroup channels, String msg, String channelKey) {if (channels != null && !channels.isEmpty()) {try {// String gzip = GZIPUtils.compress(msg); //压缩过后再二进制传输result.writeBytes(msg.getBytes());channels.writeAndFlush(new BinaryWebSocketFrame(result)).addListener(future -> {if (!future.isSuccess()) {log.error("write error", future.cause());}});} else {if (!StringUtil.isNullOrEmpty(channelKey)) {subscribersMap.remove(channelKey);}}}