List of usage examples for io.netty.buffer ByteBuf readableBytes
public abstract int readableBytes();
From source file:cloudeventbus.codec.Encoder.java
License:Open Source License
@Override public void encode(ChannelHandlerContext ctx, Frame frame, ByteBuf out) throws Exception { LOGGER.debug("Encoding frame {}", frame); switch (frame.getFrameType()) { case AUTHENTICATE: final AuthenticationRequestFrame authenticationRequestFrame = (AuthenticationRequestFrame) frame; out.writeByte(FrameType.AUTHENTICATE.getOpcode()); out.writeByte(' '); final String challenge = Base64.encodeBase64String(authenticationRequestFrame.getChallenge()); writeString(out, challenge);/*from w ww . j a v a 2 s . com*/ break; case AUTH_RESPONSE: final AuthenticationResponseFrame authenticationResponseFrame = (AuthenticationResponseFrame) frame; out.writeByte(FrameType.AUTH_RESPONSE.getOpcode()); out.writeByte(' '); // Write certificate chain final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final OutputStream base64Out = new Base64OutputStream(outputStream, true, Integer.MAX_VALUE, new byte[0]); CertificateStoreLoader.store(base64Out, authenticationResponseFrame.getCertificates()); out.writeBytes(outputStream.toByteArray()); out.writeByte(' '); // Write salt final byte[] encodedSalt = Base64.encodeBase64(authenticationResponseFrame.getSalt()); out.writeBytes(encodedSalt); out.writeByte(' '); // Write signature final byte[] encodedDigitalSignature = Base64 .encodeBase64(authenticationResponseFrame.getDigitalSignature()); out.writeBytes(encodedDigitalSignature); break; case ERROR: final ErrorFrame errorFrame = (ErrorFrame) frame; out.writeByte(FrameType.ERROR.getOpcode()); out.writeByte(' '); writeString(out, Integer.toString(errorFrame.getCode().getErrorNumber())); if (errorFrame.getMessage() != null) { out.writeByte(' '); writeString(out, errorFrame.getMessage()); } break; case GREETING: final GreetingFrame greetingFrame = (GreetingFrame) frame; out.writeByte(FrameType.GREETING.getOpcode()); out.writeByte(' '); writeString(out, Integer.toString(greetingFrame.getVersion())); out.writeByte(' '); writeString(out, greetingFrame.getAgent()); out.writeByte(' '); writeString(out, Long.toString(greetingFrame.getId())); break; case PING: out.writeByte(FrameType.PING.getOpcode()); break; case PONG: out.writeByte(FrameType.PONG.getOpcode()); break; case PUBLISH: final PublishFrame publishFrame = (PublishFrame) frame; out.writeByte(FrameType.PUBLISH.getOpcode()); out.writeByte(' '); writeString(out, publishFrame.getSubject().toString()); if (publishFrame.getReplySubject() != null) { out.writeByte(' '); writeString(out, publishFrame.getReplySubject().toString()); } out.writeByte(' '); final ByteBuf body = Unpooled.wrappedBuffer(publishFrame.getBody().getBytes(CharsetUtil.UTF_8)); writeString(out, Integer.toString(body.readableBytes())); out.writeBytes(Codec.DELIMITER); out.writeBytes(body); break; case SERVER_READY: out.writeByte(FrameType.SERVER_READY.getOpcode()); break; case SUBSCRIBE: final SubscribeFrame subscribeFrame = (SubscribeFrame) frame; out.writeByte(FrameType.SUBSCRIBE.getOpcode()); out.writeByte(' '); writeString(out, subscribeFrame.getSubject().toString()); break; case UNSUBSCRIBE: final UnsubscribeFrame unsubscribeFrame = (UnsubscribeFrame) frame; out.writeByte(FrameType.UNSUBSCRIBE.getOpcode()); out.writeByte(' '); writeString(out, unsubscribeFrame.getSubject().toString()); break; default: throw new EncodingException("Don't know how to encode message of type " + frame.getClass().getName()); } out.writeBytes(Codec.DELIMITER); }
From source file:cn.ifengkou.hestia.serialize.MessageDecoder.java
License:Apache License
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { if (in.readableBytes() < MessageDecoder.MESSAGE_LENGTH) { return;//from w w w . j av a 2s .co m } in.markReaderIndex(); int messageLength = in.readInt(); if (messageLength < 0) { ctx.close(); } if (in.readableBytes() < messageLength) { in.resetReaderIndex(); return; } else { byte[] messageBody = new byte[messageLength]; in.readBytes(messageBody); try { Object obj = messageCodecUtil.decode(messageBody); out.add(obj); } catch (IOException ex) { LOGGER.error("messageCodeUtil decode failed!", ex); } } }
From source file:cn.jpush.api.common.connection.HttpResponseHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); if (streamId == null) { System.err.println("HttpResponseHandler unexpected message received: " + msg); return;/*from w ww .j a v a 2 s. c o m*/ } else { LOG.debug("HttpResponseHandler response message received: " + msg); } Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId); List<String> list = new ArrayList<String>(); list.add(msg.status().code() + ""); if (entry == null) { System.err.println("Message received for unknown stream id " + streamId); } else { // Do stuff with the message (for now just print it) ByteBuf byteBuf = msg.content(); if (byteBuf.isReadable()) { int contentLength = byteBuf.readableBytes(); byte[] arr = new byte[contentLength]; byteBuf.readBytes(arr); String content = new String(arr, 0, contentLength, CharsetUtil.UTF_8); list.add(content); System.out.println("Protocol version: " + msg.protocolVersion()); System.out.println("status: " + list.get(0) + " response content: " + list.get(1)); LOG.debug("Protocol version: " + msg.protocolVersion()); LOG.debug("status: " + list.get(0) + " response content: " + list.get(1)); } mNettyHttp2Client.setResponse(streamId + ctx.channel().id().asShortText(), list); if (null != mCallback) { ResponseWrapper wrapper = new ResponseWrapper(); wrapper.responseCode = Integer.valueOf(list.get(0)); if (list.size() > 1) { wrapper.responseContent = list.get(1); } mCallback.onSucceed(wrapper); } entry.getValue().setSuccess(); if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; System.err.println("content: " + content.content().toString(CharsetUtil.UTF_8)); System.err.flush(); if (content instanceof LastHttpContent) { System.err.println(" end of content"); // ctx.close(); } } } }
From source file:cn.npt.net.websocket.WebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;//from w w w .ja va 2 s .c o m } // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the demo page and favicon.ico if ("/".equals(req.getUri())) { ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req)); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); HttpHeaders.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); return; } if ("/favicon.ico".equals(req.getUri())) { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); return; } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } }
From source file:cn.pengj.udpdemo.EchoSeverHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { // ??/* w w w .j a va 2 s . c o m*/ ByteBuf buf = (ByteBuf) packet.copy().content(); byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, CharsetUtil.UTF_8); System.out.println("?NOTE>>>>>> ?" + body); // ??? ctx.writeAndFlush(new DatagramPacket( Unpooled.copiedBuffer("HelloServer" + System.currentTimeMillis(), CharsetUtil.UTF_8), packet.sender())).sync(); }
From source file:cn.scujcc.bug.bitcoinplatformandroid.util.socket.websocket.WebSocketClientHandler.java
License:Apache License
public String decodeByteBuff(ByteBuf buf) throws IOException, DataFormatException { byte[] temp = new byte[buf.readableBytes()]; ByteBufInputStream bis = new ByteBufInputStream(buf); bis.read(temp);//from w w w . j a v a 2 s . c o m bis.close(); Inflater decompresser = new Inflater(true); decompresser.setInput(temp, 0, temp.length); StringBuilder sb = new StringBuilder(); byte[] result = new byte[1024]; while (!decompresser.finished()) { int resultLength = decompresser.inflate(result); sb.append(new String(result, 0, resultLength, "UTF-8")); } decompresser.end(); return sb.toString(); }
From source file:co.rsk.net.discovery.PacketDecoder.java
License:Open Source License
@Override public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception { ByteBuf buf = packet.content(); byte[] encoded = new byte[buf.readableBytes()]; buf.readBytes(encoded);//from w w w . j av a2 s . c om out.add(this.decodeMessage(ctx, encoded, packet.sender())); }
From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { RecyclableArrayList out = RecyclableArrayList.newInstance(); try {/*from w ww . j a va 2 s . co m*/ if (msg instanceof ByteBuf) { ByteBuf data = (ByteBuf) msg; if (cumulation == null) { cumulation = data; try { callDecode(ctx, cumulation, out); } finally { if (cumulation != null && !cumulation.isReadable()) { cumulation.release(); cumulation = null; } } } else { try { if (cumulation.writerIndex() > cumulation.maxCapacity() - data.readableBytes()) { ByteBuf oldCumulation = cumulation; cumulation = ctx.alloc().buffer(oldCumulation.readableBytes() + data.readableBytes()); cumulation.writeBytes(oldCumulation); oldCumulation.release(); } cumulation.writeBytes(data); callDecode(ctx, cumulation, out); } finally { if (cumulation != null) { if (!cumulation.isReadable()) { cumulation.release(); cumulation = null; } else { cumulation.discardSomeReadBytes(); } } data.release(); } } } else { out.add(msg); } } catch (DecoderException e) { throw e; } catch (Throwable t) { throw new DecoderException(t); } finally { if (out.isEmpty()) { decodeWasNull = true; } List<Object> results = new ArrayList<Object>(); for (Object result : out) { results.add(result); } ctx.fireChannelRead(results); out.recycle(); } }
From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java
License:Apache License
@Override public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception { ByteBuf buf = internalBuffer(); int readable = buf.readableBytes(); if (buf.isReadable()) { ByteBuf bytes = buf.readBytes(readable); buf.release();/*ww w .j ava2s. co m*/ ctx.fireChannelRead(bytes); } cumulation = null; ctx.fireChannelReadComplete(); handlerRemoved0(ctx); }
From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java
License:Apache License
/** * Called once data should be decoded from the given {@link ByteBuf}. This method will call * {@link #decode(ChannelHandlerContext, ByteBuf, List)} as long as decoding should take place. * * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to * @param in the {@link ByteBuf} from which to read data * @param out the {@link List} to which decoded messages should be added *///from w w w . j av a2 s .c o m protected void callDecode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { try { while (in.isReadable()) { int outSize = out.size(); int oldInputLength = in.readableBytes(); decode(ctx, in, out); // Check if this handler was removed before try to continue the loop. // If it was removed it is not safe to continue to operate on the buffer // // See https://github.com/netty/netty/issues/1664 if (ctx.isRemoved()) { break; } if (outSize == out.size()) { if (oldInputLength == in.readableBytes()) { break; } else { continue; } } if (oldInputLength == in.readableBytes()) { throw new DecoderException(StringUtil.simpleClassName(getClass()) + ".decode() did not read anything but decoded a message."); } if (isSingleDecode()) { break; } } } catch (DecoderException e) { throw e; } catch (Throwable cause) { throw new DecoderException(cause); } }