List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
From source file:p2p_server.DeviceHandler.java
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // System.out.println("Dev recv msg " + msg); Gson json = new Gson(); int msglen = msg.toString().length(); String s = msg.toString() + "\r\n"; Type type = new TypeToken<Map<String, String>>() { }.getType();//from www. j a v a 2 s .co m Map<String, String> dict; dict = json.fromJson(s.substring(2, msglen), type); String cmd = ""; try { cmd = dict.get(CMD).toString(); //System.out.println("is login " + cmd); } catch (NullPointerException e) { write_error(ctx, unkown_cmd); return; } if (cmd.compareTo(LOGIN) == 0) { // System.out.println("login ok"); String uuid = ""; String pwd = ""; try { uuid = dict.get(UUID).toString(); pwd = dict.get(PWD).toString(); } catch (NullPointerException ue) { write_error(ctx, unkown_format); return; // ue.printStackTrace(); } /*??? */ Object[] oldobj = null; try { oldobj = dc.getDevChannel(uuid); } catch (NullPointerException npe) { } if (oldobj != null) { /* ? */ Channel oldch = (Channel) oldobj[1]; Map<String, String> notifyDict = new HashMap<>(); notifyDict.put(MSG, "new login from " + ctx.channel().remoteAddress()); String jsondata = json.toJson(notifyDict); ByteBuf sendbuf = oldch.alloc().heapBuffer(jsondata.toString().length() + 4); int len = jsondata.length() + 2; byte[] lenarry = { 0x0, 0x0 }; lenarry[0] = (byte) (0xff00 & len); lenarry[1] = (byte) (0xff & len); sendbuf.writeBytes(lenarry); sendbuf.writeBytes(jsondata.toString().getBytes()); sendbuf.writeBytes("\r\n\r\n".getBytes()); ChannelFuture write = oldch.writeAndFlush(sendbuf); if (!write.isSuccess()) { System.out.println("notify new login failed: " + write.cause()); } dc.removeDevChannel(uuid); write.addListener(ChannelFutureListener.CLOSE); } dc.bandUserAndChannel(uuid, pwd, ctx.channel()); ByteBuf sendbuf = ctx.alloc().heapBuffer(msg_ok.length); sendbuf.writeBytes(msg_ok); // sendbuf.writeBytes(msg_ok); ChannelFuture write = ctx.channel().writeAndFlush(sendbuf); if (!write.isSuccess()) { System.out.println("send login failed: " + write.cause()); } } else if (0 == cmd.compareTo(KEEP)) { // System.out.println("keep ok"); ByteBuf sendbuf = ctx.alloc().heapBuffer(msg.toString().length() + 4); sendbuf.writeBytes(msg.toString().getBytes()); sendbuf.writeBytes("\r\n\r\n".getBytes()); ChannelFuture write = ctx.writeAndFlush(sendbuf); if (!write.isSuccess()) { System.out.println("send keep failed: " + write.cause()); } } else if (0 == cmd.compareTo(CONN)) { String aid = ""; try { aid = dict.get(AID); } catch (NullPointerException ue) { //ue.printStackTrace(); write_error(ctx, unkown_format); return; } // Promise<Channel> promise = ctx.executor().newPromise(); // System.out.println("recv dev conn for aid "+aid); Channel appChannel = dc.getAppChannel(aid); //System.out.println("app dict size : " + dc.getMapSize("app")); if (appChannel instanceof Channel) { // System.out.println("ready send addr to app!!!!"); ByteBuf sendbuf = appChannel.alloc().heapBuffer(msg.toString().length() + 4); sendbuf.writeBytes(msg.toString().getBytes()); sendbuf.writeBytes("\r\n\r\n".getBytes()); ChannelFuture write = appChannel.writeAndFlush(sendbuf); /* if (!write.isSuccess()) { System.out.println("send to app failed: " + write.cause()); } */ dc.removeAppChannel(aid); write.addListener(ChannelFutureListener.CLOSE); } } else { //? write_error(ctx, unkown_cmd); } }
From source file:p2p_server.DeviceHandler.java
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) { IdleStateEvent event = (IdleStateEvent) evt; // sendbuf.writeBytes(msg_ok); if (null != event.state()) { switch (event.state()) { case READER_IDLE: System.out.println("dev read idle"); break; case WRITER_IDLE: System.out.println("dev write idle"); break; case ALL_IDLE: System.out.println("dev all idle"); break; default: break; }/*from ww w . ja v a 2s .c o m*/ } ByteBuf sendbuf = ctx.alloc().heapBuffer(msg_keep.length); sendbuf.writeBytes(msg_keep); ChannelFuture write = ctx.channel().writeAndFlush(sendbuf); if (!write.isSuccess()) { System.out.println("send login failed: " + write.cause()); } } }
From source file:ratpack.server.internal.NettyHandlerAdapter.java
License:Apache License
public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest nettyRequest) throws Exception { if (!nettyRequest.decoderResult().isSuccess()) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); nettyRequest.release();/*from w w w. ja v a 2s . c o m*/ return; } final Channel channel = ctx.channel(); InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress(); InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress(); final ServerConfig serverConfig = rootRegistry.get(ServerConfig.class); final Request request = new DefaultRequest(new NettyHeadersBackedHeaders(nettyRequest.headers()), nettyRequest.method(), nettyRequest.uri(), remoteAddress, socketAddress, nettyRequest.content()); final HttpHeaders nettyHeaders = new DefaultHttpHeaders(false); final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders); final DefaultEventController<RequestOutcome> requestOutcomeEventController = new DefaultEventController<>(); final AtomicBoolean transmitted = new AtomicBoolean(false); final DefaultResponseTransmitter responseTransmitter = new DefaultResponseTransmitter(transmitted, execControl, channel, nettyRequest, request, nettyHeaders, requestOutcomeEventController); ctx.attr(RESPONSE_TRANSMITTER_ATTRIBUTE_KEY).set(responseTransmitter); Action<Action<Object>> subscribeHandler = thing -> { transmitted.set(true); ctx.attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).set(thing); }; final DirectChannelAccess directChannelAccess = new DefaultDirectChannelAccess(channel, subscribeHandler); final DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants( applicationConstants, request, directChannelAccess, requestOutcomeEventController.getRegistry()); final Response response = new DefaultResponse(execControl, responseHeaders, ctx.alloc(), responseTransmitter, requestConstants); requestConstants.response = response; DefaultContext.start(channel.eventLoop(), execController.getControl(), requestConstants, rootRegistry, handlers, execution -> { if (!transmitted.get()) { Handler lastHandler = requestConstants.handler; StringBuilder description = new StringBuilder(); description.append("No response sent for ").append(request.getMethod().getName()) .append(" request to ").append(request.getUri()).append(" (last handler: "); if (lastHandler instanceof DescribingHandler) { ((DescribingHandler) lastHandler).describeTo(description); } else { DescribingHandlers.describeTo(lastHandler, description); } description.append(")"); String message = description.toString(); LOGGER.warn(message); response.status(500); if (serverConfig.isDevelopment()) { response.send(message); } else { response.send(); } } }); }
From source file:reactor.io.net.impl.netty.NettyChannelHandlerBridge.java
License:Apache License
protected static ByteBuf convertBufferToByteBuff(ChannelHandlerContext ctx, Buffer data) { ByteBuf buff = ctx.alloc().buffer(data.remaining()); return buff.writeBytes(data.byteBuffer()); }
From source file:reactor.io.net.impl.netty.NettyChannelHandlerBridge.java
License:Apache License
private static ByteBuf createCombinedBuffer(ByteBuf partOne, ByteBuf partTwo, ChannelHandlerContext ctx) { ByteBuf combined = ctx.alloc().buffer(partOne.readableBytes() + partTwo.readableBytes()); combined.writeBytes(partOne);/* www . j a v a2 s . co m*/ combined.writeBytes(partTwo); return combined; }
From source file:reactor.io.net.impl.netty.NettyNetChannelInboundHandler.java
License:Apache License
private ByteBuf createCombinedBuffer(ByteBuf partOne, ByteBuf partTwo, ChannelHandlerContext ctx) { ByteBuf combined = ctx.alloc().buffer(partOne.readableBytes() + partTwo.readableBytes()); combined.writeBytes(partOne);/*from ww w.ja v a2s. co m*/ combined.writeBytes(partTwo); return combined; }
From source file:reactor.ipc.netty.http.client.HttpClientFormEncoder.java
License:Open Source License
@Deprecated @Override/* w ww . j a va 2 s . c om*/ public HttpContent readChunk(ChannelHandlerContext ctx) throws Exception { return readChunk(ctx.alloc()); }
From source file:ru.calypso.ogar.server.net.PacketEncoder.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override//from w ww. jav a2 s . c om protected void encode(ChannelHandlerContext ctx, Packet packet, List out) throws Exception { ByteBuf buf = ctx.alloc().buffer().order(ByteOrder.LITTLE_ENDIAN); int packetId = PacketRegistry.SERVER2CLIENT.getPacketId(packet.getClass()); if (packetId == -1) { throw new IllegalArgumentException("Provided packet is not registered as a clientbound packet!"); } buf.writeByte(packetId); packet.writeData(buf); new BinaryWebSocketFrame(buf); out.add(new BinaryWebSocketFrame(buf)); Log.logDebug("Sent packet ID " + packetId + " (" + packet.getClass().getSimpleName() + ") to " + ctx.channel().remoteAddress()); }
From source file:se.sics.kompics.network.netty.MessageEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, Msg msg, List<Object> outL) throws Exception { ByteBuf out = ctx.alloc().buffer(NettyNetwork.INITIAL_BUFFER_SIZE, NettyNetwork.SEND_BUFFER_SIZE); NettyNetwork.LOG.trace("Trying to encode outgoing data to {} from {}.", ctx.channel().remoteAddress(), ctx.channel().localAddress()); int startIdx = out.writerIndex(); out.writeBytes(LENGTH_PLACEHOLDER);/* w w w .ja va 2 s . c o m*/ Serializers.toBinary(msg, out); int endIdx = out.writerIndex(); int diff = endIdx - startIdx - LENGTH_PLACEHOLDER.length; if (diff > 65532) { //2^16 - 2bytes for the length header (snappy wants no more than 65536 bytes uncompressed) throw new Exception("Can't encode message longer than 65532 bytes!"); } out.setShort(startIdx, diff); NettyNetwork.LOG.trace("Encoded outgoing {} bytes of data to {}: {}.", new Object[] { diff, ctx.channel().remoteAddress(), ByteBufUtil.hexDump(out) }); outL.add(out); }
From source file:shi.cs.MqttEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, MqttMessage msg, List<Object> out) throws Exception { out.add(doEncode(ctx.alloc(), msg)); }