List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
From source file:com.sample.netty.socket.server.ServerHandlerOutbound.java
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { ByteBuf encoded = ctx.alloc().buffer(4); encoded.writeBytes(((String) msg).getBytes()); ctx.writeAndFlush(encoded, promise); System.err.println("[SERVER SEND MENSSAGE] " + msg); }
From source file:com.sheldon.javaPrj.netty.TimeClientHandler.java
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { buf = ctx.alloc().buffer(4); }
From source file:com.sheldon.javaPrj.netty.TimeServerHandler.java
@Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { final ByteBuf time = ctx.alloc().buffer(4); time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L)); final ChannelFuture f = ctx.writeAndFlush(time); // (3) f.addListener(new ChannelFutureListener() { @Override/* w ww. j a v a 2 s . c o m*/ public void operationComplete(ChannelFuture future) { assert f == future; ctx.close(); } }); // (4) }
From source file:com.shelf.messagepack.MessagePackFrameDecoder.java
License:Apache License
protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) { // make a sliced buffer for reading full contents, then if enough data doesn't reached yet, // ReplayingDecoder will throw an error for replaying decode operation at this line. // // w w w . j a v a2 s .c o m // Don't create a new buffer with ctx.alloc().buffer() before enough data has come. It will not be released (and leaked). // If sliced buffer is created successfully, enough data has come. ByteBuf slice = buffer.slice(index, length); ByteBuf frame = ctx.alloc().buffer(length); frame.writeBytes(slice, 0, length); return frame; }
From source file:com.spotify.folsom.client.MemcacheEncoder.java
License:Apache License
@Override public void encode(final ChannelHandlerContext ctx, final Request<?> request, final List<Object> out) throws Exception { workingBuffer.clear();/*from w ww .j a v a 2s .c om*/ final ByteBuf message = request.writeRequest(ctx.alloc(), workingBuffer); out.add(message); }
From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPFramingEncoder.java
License:Apache License
@Override public void flush(final ChannelHandlerContext ctx) throws Exception { if (messages == null) { return;/*from w w w . j a va2 s. co m*/ } estimator.reset(); for (final Object message : messages) { encoder.estimate(message, estimator); } final ByteBuf output = ctx.alloc().buffer(estimator.size()); writer.reset(output); for (final Object message : messages) { encoder.encode(message, writer); ReferenceCountUtil.release(message); } final ChannelPromise aggregate = new AggregatePromise(ctx.channel(), promises); messages.clear(); promises.clear(); ctx.write(output, aggregate); ctx.flush(); }
From source file:com.tcy.app.netty4.Ne4ClientHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; // Initialize the message. byte[] b = "Unexpected exception from downstream.".getBytes(); content = ctx.alloc().directBuffer(1).writeBytes(b); // Send the initial messages. generateTraffic();// ww w .j a v a2 s. co m }
From source file:com.tencent.mars.proxy.NetMsgHeaderHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try {/*from ww w . j a va 2 s . c o m*/ // decode request final NetMsgHeader msgXp = new NetMsgHeader(); final InputStream socketInput = new ByteBufInputStream((ByteBuf) msg); boolean ret = msgXp.decode(socketInput); IOUtils.closeQuietly(socketInput); if (!ret) return; linkTimeout.remove(ctx); linkTimeout.put(ctx, System.currentTimeMillis()); logger.info(LogUtils.format("client req, cmdId=%d, seq=%d", msgXp.cmdId, msgXp.seq)); final ProxySession proxySession = ProxySession.Manager.get(ctx); if (proxySession == null) { } String webCgi = CMD_PATH_MAP.get(msgXp.cmdId); switch (msgXp.cmdId) { case Main.CmdID.CMD_ID_HELLO_VALUE: InputStream requestDataStream = new ByteArrayInputStream(msgXp.body); InputStream inputStream = doHttpRequest(webCgi, requestDataStream); if (inputStream != null) { msgXp.body = IOUtils.toByteArray(inputStream); IOUtils.closeQuietly(requestDataStream); byte[] respBuf = msgXp.encode(); logger.info(LogUtils.format("client resp, cmdId=%d, seq=%d, resp.len=%d", msgXp.cmdId, msgXp.seq, msgXp.body == null ? 0 : msgXp.body.length)); ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(respBuf)); } else { } break; case Main.CmdID.CMD_ID_SEND_MESSAGE_VALUE: requestDataStream = new ByteArrayInputStream(msgXp.body); inputStream = doHttpRequest(webCgi, requestDataStream); if (inputStream != null) { msgXp.body = IOUtils.toByteArray(inputStream); Chat.SendMessageResponse response = Chat.SendMessageResponse.parseFrom(msgXp.body); if (response != null && response.getErrCode() == Chat.SendMessageResponse.Error.ERR_OK_VALUE) { TopicChats.getInstance().pushMessage(response.getTopic(), response.getText(), response.getFrom(), ctx); } IOUtils.closeQuietly(requestDataStream); byte[] respBuf = msgXp.encode(); logger.info(LogUtils.format("client resp, cmdId=%d, seq=%d, resp.len=%d", msgXp.cmdId, msgXp.seq, msgXp.body == null ? 0 : msgXp.body.length)); ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(respBuf)); } else { } break; case NetMsgHeader.CMDID_NOOPING: byte[] respBuf = msgXp.encode(); logger.info(LogUtils.format("client resp, cmdId=%d, seq=%d, resp.len=%d", msgXp.cmdId, msgXp.seq, msgXp.body == null ? 0 : msgXp.body.length)); ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(respBuf)); break; default: break; } } catch (Exception e) { e.printStackTrace(); } finally { ReferenceCountUtil.release(msg); } }
From source file:com.tesora.dve.db.mysql.portal.protocol.CachedAppendBuffer.java
License:Open Source License
public void allocateSlabIfNeeded(ChannelHandlerContext ctx) { if (cachedSlab != null) //we already have a slab. return;/*from www . jav a 2s. co m*/ if (PREFER_DIRECT) { cachedSlab = ctx.alloc().ioBuffer(SLAB_SIZE); } else { cachedSlab = ctx.alloc().heapBuffer(SLAB_SIZE); } cachedSlab = cachedSlab.order(ByteOrder.LITTLE_ENDIAN); }
From source file:com.tesora.dve.db.mysql.portal.protocol.MSPProtocolDecoder.java
License:Open Source License
protected void decode(final ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { try {/*from w w w. j av a 2 s . c o m*/ if (mspPacket == null) { //assumes next full inbound request will have a starting sequence (true except for auth handshake) //also assumes we only get one request at a time (synchronous), which is typical of most mysql clients int seq = firstPacket ? 1 : 0; mspPacket = new Packet(ctx.alloc(), seq, Packet.Modifier.HEAPCOPY_ON_READ, "frontend"); } //deals with the handshake packet firstPacket = false; if (!mspPacket.decodeMore(in)) return; int sequenceId = mspPacket.getSequenceNumber(); this.nextSequence = (byte) (0xFF & mspPacket.getNextSequenceNumber()); //save off the sequence for our outbound response. ByteBuf payload = mspPacket.unwrapPayload().retain();//retain a separate reference to the payload. mspPacket.release(); mspPacket = null; final MyDecoderState state = currentState; switch (state) { case READ_SERVER_GREETING: case READ_CLIENT_AUTH: { MSPMessage authMessage; if (state == MyDecoderState.READ_CLIENT_AUTH) { authMessage = MSPAuthenticateV10MessageMessage.newMessage(payload); } else if (state == MyDecoderState.READ_SERVER_GREETING) { authMessage = new MSPServerGreetingRequestMessage(payload); } else { throw new PECodingException("Unexpected state in packet decoding, " + state); } out.add(authMessage); this.currentState = MyDecoderState.READ_PACKET; break; } case READ_PACKET: out.add(buildMessage(payload, (byte) sequenceId)); break; } } catch (Exception e) { LoggerFactory.getLogger(MSPProtocolDecoder.class).warn("problem decoding frame", e); } finally { } }