io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame Java Examples

The following examples show how to use io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LogUtil.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Print {@link WebSocketFrame} information.
 *
 * @param log              {@link Log} object of the relevant class
 * @param frame            {@link WebSocketFrame} frame
 * @param channelContextId {@link ChannelHandlerContext} context id as a String
 * @param customMsg        Log message which needs to be appended to the frame information,
 *                         if it is not required provide null
 * @param isInbound        true if the frame is inbound, false if it is outbound
 */
private static void printWebSocketFrame(
        Log log, WebSocketFrame frame, String channelContextId,
        String customMsg, boolean isInbound) {

    String logStatement = getDirectionString(isInbound) + channelContextId;
    if (frame instanceof PingWebSocketFrame) {
        logStatement += " Ping frame";
    } else if (frame instanceof PongWebSocketFrame) {
        logStatement += " Pong frame";
    } else if (frame instanceof CloseWebSocketFrame) {
        logStatement += " Close frame";
    } else if (frame instanceof BinaryWebSocketFrame) {
        logStatement += " Binary frame";
    } else if (frame instanceof TextWebSocketFrame) {
        logStatement += " " + ((TextWebSocketFrame) frame).text();
    }

    //specifically for logging close websocket frames with error status
    if (customMsg != null) {
        logStatement += " " + customMsg;
    }
    log.debug(logStatement);

}
 
Example #2
Source File: FrameCodec.java    From bitchat with Apache License 2.0 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
    ByteBuf in = ByteBufAllocator.DEFAULT.buffer();
    // check the frame
    if (!checkFrame(frame)) {
        throw new RuntimeException("checkFrame failed!");
    }
    // get frame content bytes
    byte[] content = serializer.serialize(frame);
    // do encode
    in.writeByte(frame.getMagic());
    in.writeByte(frame.getType());
    in.writeInt(content.length);
    in.writeBytes(content);

    out.add(new BinaryWebSocketFrame(in));
}
 
Example #3
Source File: WebSocketUpgradeHandler.java    From selenium with Apache License 2.0 6 votes vote down vote up
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
  if (frame instanceof CloseWebSocketFrame) {
    handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
    // Pass on to the rest of the channel
    ctx.fireChannelRead(frame);
  } else if (frame instanceof PingWebSocketFrame) {
    ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()));
  } else if (frame instanceof ContinuationWebSocketFrame) {
    ctx.write(frame);
  } else if (frame instanceof PongWebSocketFrame) {
    frame.release();
  } else if (frame instanceof BinaryWebSocketFrame || frame instanceof TextWebSocketFrame) {
    // Allow the rest of the pipeline to deal with this.
    ctx.fireChannelRead(frame);
  } else {
    throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
      .getName()));
  }
}
 
Example #4
Source File: PojoEndpointServer.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public void doOnBinary(Channel channel, WebSocketFrame frame) {
    Attribute<String> attrPath = channel.attr(PATH_KEY);
    PojoMethodMapping methodMapping = null;
    if (pathMethodMappingMap.size() == 1) {
        methodMapping = pathMethodMappingMap.values().iterator().next();
    } else {
        String path = attrPath.get();
        methodMapping = pathMethodMappingMap.get(path);
    }
    if (methodMapping.getOnBinary() != null) {
        BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) frame;
        Object implement = channel.attr(POJO_KEY).get();
        try {
            methodMapping.getOnBinary().invoke(implement, methodMapping.getOnBinaryArgs(channel, binaryWebSocketFrame));
        } catch (Throwable t) {
            logger.error(t);
        }
    }
}
 
Example #5
Source File: AutobahnServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format(
                "Channel %s received %s", ctx.channel().hashCode(), StringUtil.simpleClassName(frame)));
    }

    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
    } else if (frame instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()), ctx.voidPromise());
    } else if (frame instanceof TextWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof BinaryWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof ContinuationWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof PongWebSocketFrame) {
        frame.release();
        // Ignore
    } else {
        throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
                .getName()));
    }
}
 
Example #6
Source File: WSMessageEncoder.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    log.debug("In webapp socket encoder {}", msg);
    if (msg instanceof MessageBase) {
        MessageBase message = (MessageBase) msg;
        ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
        out.writeByte(message.command);
        out.writeShort(message.id);

        if (message instanceof ResponseMessage) {
            out.writeInt(((ResponseMessage) message).code);
        } else {
            byte[] body = message.getBytes();
            if (body.length > 0) {
                out.writeBytes(body);
            }
        }
        super.write(ctx, new BinaryWebSocketFrame(out), promise);
    } else {
        super.write(ctx, msg, promise);
    }
}
 
Example #7
Source File: HttpServerHandler.java    From ext-opensource-netty with Mozilla Public License 2.0 6 votes vote down vote up
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
	if (frame instanceof CloseWebSocketFrame) {
		handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
		return;
	}
	if (frame instanceof PingWebSocketFrame) {
		ctx.writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
		return;
	}
	if (frame instanceof TextWebSocketFrame) {
		if (webSocketEvent != null) {
			webSocketEvent.onMessageStringEvent(baseServer, new WebSocketSession(ctx.channel()), ((TextWebSocketFrame) frame).text());
		}
		return;
	}
	
	if (frame instanceof BinaryWebSocketFrame) {
		if (webSocketEvent != null) {
			webSocketEvent.onMessageBinaryEvent(baseServer, new WebSocketSession(ctx.channel()), ((BinaryWebSocketFrame)frame).content());
		}
	}
}
 
Example #8
Source File: GatewayHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
void sendMetrics(@Nullable JsonObject metrics) {
   ChannelHandlerContext c = ctx;
   if (metrics == null || !connected) {
      return;
   }

   try {
      String spayload = JSON.toJson(metrics);
      byte[] payload = spayload.getBytes(StandardCharsets.UTF_8);

      ByteBuf buffer = c.alloc().ioBuffer();
      OutputStream out = new ByteBufOutputStream(buffer);
      hubSerializer.serialize(HubMessage.createMetrics(payload), out);
      IOUtils.closeQuietly(out);

      BinaryWebSocketFrame frame = new BinaryWebSocketFrame(buffer);
      c.writeAndFlush(frame);

      lastHubMsg = System.nanoTime();
   } catch (IOException ex) {
      log.warn("metrics serialization failed, dropping message", ex);
   }
}
 
Example #9
Source File: NettyServer.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    LOG.trace("NettyServerHandler: Channel write: {}", msg);
    if (isWebSocketServer() && msg instanceof ByteBuf) {
        if (isFragmentWrites()) {
            ByteBuf orig = (ByteBuf) msg;
            int origIndex = orig.readerIndex();
            int split = orig.readableBytes()/2;

            ByteBuf part1 = orig.copy(origIndex, split);
            LOG.trace("NettyServerHandler: Part1: {}", part1);
            orig.readerIndex(origIndex + split);
            LOG.trace("NettyServerHandler: Part2: {}", orig);

            BinaryWebSocketFrame frame1 = new BinaryWebSocketFrame(false, 0, part1);
            ctx.writeAndFlush(frame1);
            ContinuationWebSocketFrame frame2 = new ContinuationWebSocketFrame(true, 0, orig);
            ctx.write(frame2, promise);
        } else {
            BinaryWebSocketFrame frame = new BinaryWebSocketFrame((ByteBuf) msg);
            ctx.write(frame, promise);
        }
    } else {
        ctx.write(msg, promise);
    }
}
 
Example #10
Source File: WebSocketServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // Check for closing frame
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        if (frame instanceof PingWebSocketFrame) {
            ctx.write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        if (frame instanceof TextWebSocketFrame) {
            // Echo the frame
            ctx.write(frame.retain());
            return;
        }
        if (frame instanceof BinaryWebSocketFrame) {
            // Echo the frame
            ctx.write(frame.retain());
            return;
        }
    }
 
Example #11
Source File: PacketEncoder.java    From Ogar2-Server with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, Packet packet, List out) throws Exception {
    ByteBuf buf = ctx.alloc().buffer().order(ByteOrder.LITTLE_ENDIAN);
    int packetId = PacketRegistry.CLIENTBOUND.getPacketId(packet.getClass());
    if (packetId == -1) {
        throw new IllegalArgumentException("Provided packet is not registered as a clientbound packet!");
    }

    buf.writeByte(packetId);
    packet.writeData(buf);
    out.add(new BinaryWebSocketFrame(buf));

    OgarServer.log.finest("Sent packet ID " + packetId + " (" + packet.getClass().getSimpleName() + ") to " + ctx.channel().remoteAddress());
}
 
Example #12
Source File: PerFrameDeflateEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean acceptOutboundMessage(Object msg) throws Exception {
    return (msg instanceof TextWebSocketFrame ||
            msg instanceof BinaryWebSocketFrame ||
            msg instanceof ContinuationWebSocketFrame) &&
                ((WebSocketFrame) msg).content().readableBytes() > 0 &&
                (((WebSocketFrame) msg).rsv() & WebSocketExtension.RSV1) == 0;
}
 
Example #13
Source File: NettyAcceptor.java    From cloud-pubsub-mqtt-proxy with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext chc, ByteBuf bb, List<Object> out)
    throws Exception {
  //convert the ByteBuf to a WebSocketFrame
  BinaryWebSocketFrame result = new BinaryWebSocketFrame();
  //System.out.println("ByteBufToWebSocketFrameEncoder encode - " + ByteBufUtil.hexDump(bb));
  result.content().writeBytes(bb);
  out.add(result);
}
 
Example #14
Source File: PerMessageDeflateDecoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompressedFrame() {
    EmbeddedChannel encoderChannel = new EmbeddedChannel(
            ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8));
    EmbeddedChannel decoderChannel = new EmbeddedChannel(new PerMessageDeflateDecoder(false));

    // initialize
    byte[] payload = new byte[300];
    random.nextBytes(payload);

    encoderChannel.writeOutbound(Unpooled.wrappedBuffer(payload));
    ByteBuf compressedPayload = encoderChannel.readOutbound();

    BinaryWebSocketFrame compressedFrame = new BinaryWebSocketFrame(true,
            WebSocketExtension.RSV1 | WebSocketExtension.RSV3,
            compressedPayload.slice(0, compressedPayload.readableBytes() - 4));

    // execute
    decoderChannel.writeInbound(compressedFrame);
    BinaryWebSocketFrame uncompressedFrame = decoderChannel.readInbound();

    // test
    assertNotNull(uncompressedFrame);
    assertNotNull(uncompressedFrame.content());
    assertTrue(uncompressedFrame instanceof BinaryWebSocketFrame);
    assertEquals(WebSocketExtension.RSV3, uncompressedFrame.rsv());
    assertEquals(300, uncompressedFrame.content().readableBytes());

    byte[] finalPayload = new byte[300];
    uncompressedFrame.content().readBytes(finalPayload);
    assertTrue(Arrays.equals(finalPayload, payload));
    uncompressedFrame.release();
}
 
Example #15
Source File: PerMessageDeflateDecoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testNormalFrame() {
    EmbeddedChannel decoderChannel = new EmbeddedChannel(new PerMessageDeflateDecoder(false));

    // initialize
    byte[] payload = new byte[300];
    random.nextBytes(payload);

    BinaryWebSocketFrame frame = new BinaryWebSocketFrame(true,
            WebSocketExtension.RSV3, Unpooled.wrappedBuffer(payload));

    // execute
    decoderChannel.writeInbound(frame);
    BinaryWebSocketFrame newFrame = decoderChannel.readInbound();

    // test
    assertNotNull(newFrame);
    assertNotNull(newFrame.content());
    assertTrue(newFrame instanceof BinaryWebSocketFrame);
    assertEquals(WebSocketExtension.RSV3, newFrame.rsv());
    assertEquals(300, newFrame.content().readableBytes());

    byte[] finalPayload = new byte[300];
    newFrame.content().readBytes(finalPayload);
    assertTrue(Arrays.equals(finalPayload, payload));
    newFrame.release();
}
 
Example #16
Source File: PerFrameDeflateEncoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompressedFrame() {
    EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false));
    EmbeddedChannel decoderChannel = new EmbeddedChannel(
            ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE));

    // initialize
    byte[] payload = new byte[300];
    random.nextBytes(payload);
    BinaryWebSocketFrame frame = new BinaryWebSocketFrame(true,
            WebSocketExtension.RSV3, Unpooled.wrappedBuffer(payload));

    // execute
    encoderChannel.writeOutbound(frame);
    BinaryWebSocketFrame compressedFrame = encoderChannel.readOutbound();

    // test
    assertNotNull(compressedFrame);
    assertNotNull(compressedFrame.content());
    assertTrue(compressedFrame instanceof BinaryWebSocketFrame);
    assertEquals(WebSocketExtension.RSV1 | WebSocketExtension.RSV3, compressedFrame.rsv());

    decoderChannel.writeInbound(compressedFrame.content());
    decoderChannel.writeInbound(DeflateDecoder.FRAME_TAIL);
    ByteBuf uncompressedPayload = decoderChannel.readInbound();
    assertEquals(300, uncompressedPayload.readableBytes());

    byte[] finalPayload = new byte[300];
    uncompressedPayload.readBytes(finalPayload);
    assertTrue(Arrays.equals(finalPayload, payload));
    uncompressedPayload.release();
}
 
Example #17
Source File: WebSocketFrameEncoderTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteSingleFrame() throws Exception {
   String content = "Content MSG length less than max frame payload length: " + maxFramePayloadLength;
   ByteBuf msg = Unpooled.copiedBuffer(content, StandardCharsets.UTF_8);
   ArgumentCaptor<WebSocketFrame> frameCaptor = ArgumentCaptor.forClass(WebSocketFrame.class);

   spy.write(ctx, msg, promise); //test

   assertEquals(0, msg.readableBytes());
   verify(ctx).writeAndFlush(frameCaptor.capture(), eq(promise));
   WebSocketFrame frame = frameCaptor.getValue();
   assertTrue(frame instanceof BinaryWebSocketFrame);
   assertTrue(frame.isFinalFragment());
   assertEquals(content, frame.content().toString(StandardCharsets.UTF_8));
}
 
Example #18
Source File: WebSocketClientHandler.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        log.trace("WebSocket Client connected!");
        if (handshakeFuture != null) {
            handshakeFuture.setSuccess();
        }
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.status() +
                        ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        log.trace("WebSocket Client received message: " + binaryFrame.content());
        ctx.fireChannelRead(binaryFrame.retain().content());
    } else if (frame instanceof CloseWebSocketFrame) {
        log.trace("WebSocket Client received closing");
        ch.close();
    }
}
 
Example #19
Source File: WSWrapperEncoder.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (ctx.channel().isWritable()) {
        if (msg instanceof ByteBuf) {
            super.write(ctx, new BinaryWebSocketFrame((ByteBuf) msg), promise);
        } else {
            super.write(ctx, msg, promise);
        }
    }
}
 
Example #20
Source File: WebSocketServerHandlerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testRead0HandleBinaryFrame() throws Exception {
   ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
   Object msg = new BinaryWebSocketFrame();

   spy.channelRead0(ctx, msg); //test

   verify(spy).channelRead0(ctx, msg);
   verify(ctx).fireChannelRead(any(ByteBuf.class));
   verifyNoMoreInteractions(spy, ctx);
}
 
Example #21
Source File: WSMessageDecoder.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    log.debug("In webappdecoder. {}", msg);
    if (msg instanceof BinaryWebSocketFrame) {
        try {
            ByteBuf in = ((BinaryWebSocketFrame) msg).content();

            short command = in.readUnsignedByte();
            int messageId = in.readUnsignedShort();

            if (limitChecker.quotaReached(ctx, messageId)) {
                return;
            }

            MessageBase message;
            if (command == Command.RESPONSE) {
                message = new ResponseMessage(messageId, (int) in.readUnsignedInt());
            } else {
                int codeOrLength = in.capacity() - 3;
                message = produce(messageId, command, (String) in.readCharSequence(codeOrLength, UTF_8));
            }

            log.trace("Incoming websocket msg {}", message);
            stats.markWithoutGlobal(Command.WEB_SOCKETS);
            ctx.fireChannelRead(message);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    } else {
        super.channelRead(ctx, msg);
    }
}
 
Example #22
Source File: PerMessageDeflateDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean acceptInboundMessage(Object msg) throws Exception {
    return ((msg instanceof TextWebSocketFrame ||
             msg instanceof BinaryWebSocketFrame) &&
                (((WebSocketFrame) msg).rsv() & WebSocketExtension.RSV1) > 0) ||
            (msg instanceof ContinuationWebSocketFrame && compressing);
}
 
Example #23
Source File: WebSocketClientHandler.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    moniter.updateTime();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.getStatus() +
                        ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
    	 TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
    	 service.onReceive(textFrame.text());
    } else if (frame instanceof BinaryWebSocketFrame) {
    	BinaryWebSocketFrame binaryFrame=(BinaryWebSocketFrame)frame;
    	service.onReceive(decodeByteBuff(binaryFrame.content()));
    }else if (frame instanceof PongWebSocketFrame) {
        System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        System.out.println("WebSocket Client received closing");
        ch.close();
    }
}
 
Example #24
Source File: AppWebSocketClientHandler.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        log.trace("WebSocket Client connected!");
        if (handshakeFuture != null) {
            handshakeFuture.setSuccess();
        }
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.status() +
                        ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')');
    }

    if (msg instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
        log.trace("WebSocket Client received message: " + frame.content());
        ctx.fireChannelRead(((WebSocketFrame) msg).retain());
    } else if (msg instanceof CloseWebSocketFrame) {
        log.trace("WebSocket Client received closing");
        ch.close();
    }
}
 
Example #25
Source File: GatewayHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
void sendLogs(BlockingQueue<JsonObject> logs) {
   ChannelHandlerContext c = ctx;
   if (c == null || logs.isEmpty() || !connected) {
      return;
   }

   JsonArray lgs = new JsonArray();
   for (int i = 0; i < 1024; ++i) {
      JsonObject next = logs.poll();
      if (next == null) {
         break;
      }

      lgs.add(next);
   }

   try {
      String spayload = JSON.toJson(lgs);
      byte[] payload = spayload.getBytes(StandardCharsets.UTF_8);

      ByteBuf buffer = c.alloc().ioBuffer();
      ByteBufOutputStream out = new ByteBufOutputStream(buffer);
      hubSerializer.serialize(HubMessage.createLog(payload), out);
      IOUtils.closeQuietly(out);

      BinaryWebSocketFrame frame = new BinaryWebSocketFrame(buffer);
      c.writeAndFlush(frame);

      lastHubMsg = System.nanoTime();
   } catch (IOException ex) {
      log.warn("log serialization failed, dropping message", ex);
   }
}
 
Example #26
Source File: GatewayHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public boolean send(PlatformMessage msg, boolean checkAuth) {
   Address address = msg.getDestination();
   if (address.isHubAddress() && !address.isBroadcast()) {
      return true;
   }

   ChannelHandlerContext c = ctx;
   if (c == null || c.channel() == null || (checkAuth && !authorized.get())) {
      return false;
   }

   try {
      ByteBuf buffer = ctx.alloc().ioBuffer();
      byte[] payload = platformSerializer.serialize(msg);
      ByteBufOutputStream out = new ByteBufOutputStream(buffer);
      hubSerializer.serialize(HubMessage.createPlatform(payload), out);
      IOUtils.closeQuietly(out);

      BinaryWebSocketFrame frame = new BinaryWebSocketFrame(buffer);
      c.writeAndFlush(frame);
      lastHubMsg = System.nanoTime();

      return true;
   } catch (IOException ex) {
      log.warn("gateway serialization failed, dropping message: {}", msg);
      return true;
   }
}
 
Example #27
Source File: ProtocolWebSocketServerHandler.java    From hxy-socket with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void doMessage(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (frame instanceof BinaryWebSocketFrame) {
        byte[] contentBytes = new byte[frame.content().readableBytes()];
        frame.content().readBytes(contentBytes);
        doHandler(() -> socketMsgHandler.onMessage(ctx, contentBytes), ctx);
    }
}
 
Example #28
Source File: WebSocketBinaryFrameHandlerTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Test
public void test_unwrap_byte_buffer() throws Exception {

    final ByteBuf expected = Unpooled.buffer();
    final BinaryWebSocketFrame frame = new BinaryWebSocketFrame(expected);
    channel.writeInbound(frame);

    final Object object = channel.readInbound();
    final ByteBuf result = (ByteBuf) object;

    assertEquals(expected, result);
    assertEquals(1, result.refCnt());
}
 
Example #29
Source File: WebSocketBinaryFrameByteBufAdapter.java    From util4j with Apache License 2.0 5 votes vote down vote up
/**
 * 将webSocket消息转换为bytebuf类型,以适配后面的解码器
 */
@Override
protected void decode(ChannelHandlerContext paramChannelHandlerContext,
		WebSocketFrame paramINBOUND_IN, List<Object> paramList)
		throws Exception {
	if(paramINBOUND_IN instanceof BinaryWebSocketFrame)
	{
		BinaryWebSocketFrame msg=(BinaryWebSocketFrame)paramINBOUND_IN;
		ByteBuf data = msg.content();
		paramList.add(data);
		data.retain();
	}
}
 
Example #30
Source File: PerMessageDeflateEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, WebSocketFrame msg,
        List<Object> out) throws Exception {
    super.encode(ctx, msg, out);

    if (msg.isFinalFragment()) {
        compressing = false;
    } else if (msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame) {
        compressing = true;
    }
}