List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
From source file:com.tesora.dve.db.mysql.portal.protocol.MyBackendDecoder.java
License:Open Source License
protected void decode0(ChannelHandlerContext ctx, ByteBuf in, List<Object> out, boolean lastPacket) throws Exception { if (logger.isDebugEnabled()) logger.debug("processing packet, " + in); try {//from www . ja v a2 s. c o m //get a contextual parser that decodes data based on what was previously transmitted, never null. ParseStrategy responseParser = lookupParser(); int expectedSequence = responseParser.nextSequenceNumber(); if (mspPacket == null) mspPacket = new Packet(ctx.alloc(), expectedSequence, Packet.Modifier.HEAPCOPY_ON_READ, "backend"); if (!mspPacket.decodeMore(in)) //deals with framing and extended packets. return; //we got a packet, maybe extended. update the next expected sequence (might be > +1, if extended) responseParser.setNextSequenceNumber(mspPacket.getNextSequenceNumber()); ByteBuf leHeader = mspPacket.unwrapHeader().order(ByteOrder.LITTLE_ENDIAN).retain(); ByteBuf lePayload = mspPacket.unwrapPayload().order(ByteOrder.LITTLE_ENDIAN).retain();//retain a separate reference to the payload. mspPacket.release(); mspPacket = null; //ok, we aren't waiting for a packet anymore, end the wait timer, start the decode timer. responseParser.endAtomicWaitTimer(); Timer decodeTimer = responseParser.getNewSubTimer(TimingDesc.BACKEND_DECODE); //use the active response parser to decode the buffer into a protocol message. MyMessage message = responseParser.parsePacket(ctx, leHeader, lePayload); decodeTimer.end(socketDesc, (message == null ? "null" : message.getClass().getName())); lookupParser();//check if we are done and pop the parser now, to reduce memory usage and get tighter timer measurements. if (message != null) { out.add(message); } } catch (Exception e) { logger.warn(String.format("Unexpected problem parsing frame, closing %s :", socketDesc), e); ctx.close(); } }
From source file:com.topsec.bdc.platform.api.test.discard.DiscardClientHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { this.ctx = ctx; // Initialize the message. content = ctx.alloc().directBuffer(DiscardClient.SIZE).writeZero(DiscardClient.SIZE); // Send the initial messages. generateTraffic();/*from www . j a v a2 s .c o m*/ }
From source file:com.torchmind.netty.msgpack.codec.MessageFrameCodec.java
License:Apache License
/** * {@inheritDoc}// w ww. ja v a 2 s . c o m */ @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { while (in.readableBytes() >= 4) { // mark reader index in.markReaderIndex(); // read length int length = in.readInt(); // check whether enough data is available if (length > in.readableBytes()) { // reset index in.resetReaderIndex(); // skip further execution due to missing data break; } // read buffer ByteBuf buffer = ctx.alloc().buffer(length); in.readBytes(buffer); // append to output out.add(buffer); } }
From source file:com.turo.pushy.apns.ApnsClientHandler.java
License:Open Source License
private void writePushNotification(final ChannelHandlerContext context, final PushNotificationPromise responsePromise, final ChannelPromise writePromise) { if (context.channel().isActive()) { final int streamId = this.connection().local().incrementAndGetNextStreamId(); if (streamId > 0) { // We'll attach the push notification and response promise to the stream as soon as the stream is created. // Because we're using a StreamBufferingEncoder under the hood, there's no guarantee as to when the stream // will actually be created, and so we attach these in the onStreamAdded listener to make sure everything // is happening in a predictable order. this.unattachedResponsePromisesByStreamId.put(streamId, responsePromise); final ApnsPushNotification pushNotification = responsePromise.getPushNotification(); final Http2Headers headers = getHeadersForPushNotification(pushNotification, streamId); final ChannelPromise headersPromise = context.newPromise(); this.encoder().writeHeaders(context, streamId, headers, 0, false, headersPromise); log.trace("Wrote headers on stream {}: {}", streamId, headers); final ByteBuf payloadBuffer = context.alloc().ioBuffer(INITIAL_PAYLOAD_BUFFER_CAPACITY); payloadBuffer.writeBytes(pushNotification.getPayload().getBytes(StandardCharsets.UTF_8)); final ChannelPromise dataPromise = context.newPromise(); this.encoder().writeData(context, streamId, payloadBuffer, 0, true, dataPromise); log.trace("Wrote payload on stream {}: {}", streamId, pushNotification.getPayload()); final PromiseCombiner promiseCombiner = new PromiseCombiner(); promiseCombiner.addAll((ChannelFuture) headersPromise, dataPromise); promiseCombiner.finish(writePromise); writePromise.addListener(new GenericFutureListener<ChannelPromise>() { @Override/*from w ww .j ava 2 s .co m*/ public void operationComplete(final ChannelPromise future) { if (!future.isSuccess()) { log.trace("Failed to write push notification on stream {}.", streamId, future.cause()); responsePromise.tryFailure(future.cause()); } } }); } else { // This is very unlikely, but in the event that we run out of stream IDs, we need to open a new // connection. Just closing the context should be enough; automatic reconnection should take things // from there. writePromise.tryFailure(STREAMS_EXHAUSTED_EXCEPTION); context.channel().close(); } } else { writePromise.tryFailure(STREAM_CLOSED_BEFORE_REPLY_EXCEPTION); } }
From source file:com.uber.tchannel.codecs.MessageCodec.java
License:Open Source License
public static ChannelFuture write(ChannelHandlerContext ctx, Frame frame) { ChannelFuture f = ctx.writeAndFlush(encode(ctx.alloc(), encode(ctx.alloc(), frame))); f.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); return f;/*w ww . j av a 2 s. c o m*/ }
From source file:com.uber.tchannel.handlers.MessageFragmenter.java
License:Open Source License
protected void writeFrames(ChannelHandlerContext ctx, RawMessage msg, List<Object> frames) throws Exception { List<ByteBuf> args = new ArrayList<>(); args.add(msg.getArg1());//from w ww . j a va 2 s.c o m args.add(msg.getArg2()); args.add(msg.getArg3()); CallFrame frame = null; while (!args.isEmpty()) { if (frame == null || frame.isPayloadFull()) { frame = createFrame(msg, args.size()); } frame.encodePayload(ctx.alloc(), args); frames.add(MessageCodec.encode(ctx.alloc(), MessageCodec.encode(ctx.alloc(), frame))); } }
From source file:com.uber.tchannel.handlers.PingHandler.java
License:Open Source License
@Override protected void messageReceived(ChannelHandlerContext ctx, PingRequestFrame msg) throws Exception { ctx.writeAndFlush(MessageCodec.encode(ctx.alloc(), new PingResponseFrame(msg.getId()))); }
From source file:com.vethrfolnir.game.network.mu.MuChannelHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buff = (msg instanceof ByteBuffer) ? ctx.alloc().buffer().writeBytes((ByteBuffer) msg) : (ByteBuf) msg;/*from w ww. j a v a2 s . c om*/ buff.readerIndex(2); int opcode = buff.readUnsignedByte(); switch (opcode) { // double opcode case 0xf1: case 0xf3: case 0x0e: case 0x03: buff.readerIndex(buff.readerIndex() - 1); opcode = buff.readUnsignedShort(); // ex 0xF1_03 break; default: break; } if (opcode == 0xe00) { // Time packet? buff.clear(); buff.release(); return; } ReadPacket packet = clientpackets.get(opcode); if (packet != null) { MuClient client = ctx.channel().attr(MuClient.ClientKey).get(); //System.out.println("Got opcode: 0x"+PrintData.fillHex(opcode, 2)+ " packet = \n"+packet.getClass().getSimpleName()); packet.read(client, buff); } else { log.warn("Unknown packet[opcode = 0x" + PrintData.fillHex(opcode, 2) + "]. Dump: "); log.warn(PrintData.printData(buff.nioBuffer(0, buff.writerIndex()))); } //log.warn(PrintData.printData(buff.nioBuffer(0, buff.writerIndex()))); if (buff.refCnt() > 0) { //System.out.println("Handler Release when packet[opcode = 0x"+PrintData.fillHex(opcode, 2)+"]"); buff.release(); } }
From source file:com.vethrfolnir.game.network.mu.MuCyperDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (!in.isReadable()) { MuClient client = ctx.channel().attr(MuClient.ClientKey).get(); _log.warn("Client[" + client + "] sent an empty packet!"); return; //XXX: is it critical? }/* w w w . j av a2s . c om*/ if (in.readableBytes() < 3) { return; // come back later } in.markReaderIndex(); int opcode = in.readUnsignedByte(); int lengthAt = 0; switch (opcode) { case 0xc1: case 0xc3: lengthAt = 1; break; case 0xc2: case 0xc4: lengthAt = 2; break; } //in.markReaderIndex(); int rez = lengthAt > 1 ? in.readShort() : in.readUnsignedByte(); in.resetReaderIndex(); //System.out.println("1 Size[point="+(lengthAt > 1 ? "Short" : "Unsigned byte")+"]: "+rez+" opcode "+Integer.toHexString(opcode & 0xFF)); if (in.readableBytes() < rez) { in.resetReaderIndex(); return; } int header = in.getUnsignedByte(0); if (header == 0xC1 || header == 0xC2) { ByteBuf buff = ctx.alloc().heapBuffer(rez); in.readBytes(buff); out.add(DecodeXor32(buff)); } else { out.add(DecodePacket(in)); } }
From source file:com.vethrfolnir.login.network.mu.ClientChannelHandler.java
License:Open Source License
@Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { if (nameService.liveServerSize() > 0) { ByteBuf buff = ctx.alloc().buffer(4); ctx.writeAndFlush(buff.writeBytes(new byte[] { (byte) 0xC1, 0x04, 0x00, 0x01 })); }//from w w w . j a v a 2s . c o m }