List of usage examples for io.netty.buffer ByteBuf release
boolean release();
From source file:com.zhucode.longio.transport.netty.RawSocketClientHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception { ByteBuf buf = (ByteBuf) message; byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes);/*from ww w . j a v a 2 s. c o m*/ try { MessageBlock mb = pp.decode(bytes); if (mb.getCmd() == 0) { ctx.fireUserEventTriggered(new PingEvent()); return; } processRevMessage(ctx, mb); } catch (ProtocolException e) { e.printStackTrace(); } finally { buf.release(); } }
From source file:com.zhucode.longio.transport.netty.RawSocketHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception { ByteBuf buf = (ByteBuf) message; try {// w ww . j a v a 2 s . c om process(ctx, buf); } finally { buf.release(); } }
From source file:controlspy3.SpyAsServer.java
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("\nrecibio algo Servidor"); ByteBuf in = (ByteBuf) msg; ArrayList in2 = new ArrayList(); String messageServer = ""; try {//from w w w . j av a 2 s . c om while (in.isReadable()) { // (1) byte rxByte = in.readByte(); in2.add(rxByte); } ux1 = new UnixTime1(in2); System.out.println("A"); SpyAsServer.channelSend(); messageServer = ""; for (int i = 0; i < in2.size(); i++) { byte rxByte = (byte) in2.get(i); messageServer += String.valueOf(Character.toChars(rxByte)); } } catch (Exception e) { System.out.println("Entro al ERROR RARO"); } finally { in.release(); // (2) } }
From source file:de.dfki.kiara.http.HttpRequestMessage.java
License:Open Source License
public HttpRequest finalizeRequest() { request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, getPayload().remaining()); ByteBuf bbuf = Unpooled.wrappedBuffer(getPayload()); ByteBuf byteContent = content.content().clear(); byteContent.writeBytes(bbuf);//from www. j av a 2 s. c o m bbuf.release(); return request; }
From source file:de.jackwhite20.apex.udp.pipeline.DatagramUpstreamHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket datagramPacket) throws Exception { BackendInfo backendInfo = ApexDatagram.getBalancingStrategy().selectBackend("", 0); if (backendInfo == null) { logger.error("Unable to select a backend server. All down?"); return;/* w w w. ja va 2s . co m*/ } // Only copy if there is at least one backend server ByteBuf copy = datagramPacket.content().copy().retain(); Bootstrap bootstrap = new Bootstrap().channel(PipelineUtils.getDatagramChannel()) .handler(new DatagramDownstreamHandler(ctx.channel(), datagramPacket.sender())) .group(ctx.channel().eventLoop()); ChannelFuture channelFuture = bootstrap.bind(0); // Add the traffic shaping handler to the channel pipeline GlobalTrafficShapingHandler trafficShapingHandler = Apex.getInstance().getTrafficShapingHandler(); if (trafficShapingHandler != null) { // The handler needs to be the first handler in the pipeline channelFuture.channel().pipeline().addFirst(trafficShapingHandler); } channelFuture.addListener((ChannelFutureListener) channelFuture1 -> { Channel channel = channelFuture1.channel(); if (channelFuture1.isSuccess()) { channel.writeAndFlush(new DatagramPacket(copy, new InetSocketAddress(backendInfo.getHost(), backendInfo.getPort()))); } else { ChannelUtil.close(channel); } // Release the buffer copy.release(); }); // Keep track of request per second if (connectionsPerSecondTask != null) { connectionsPerSecondTask.inc(); } }
From source file:deathcap.wsmc.web.HTTPHandler.java
License:Apache License
public void httpRequest(ChannelHandlerContext context, FullHttpRequest request) throws IOException { if (!request.getDecoderResult().isSuccess()) { sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;//from w w w .java 2s.c om } if (request.getUri().equals("/server")) { context.fireChannelRead(request); return; } if ((request.getMethod() == OPTIONS || request.getMethod() == HEAD) && request.getUri().equals("/chunk")) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Methods", "POST"); if (request.getMethod() == OPTIONS) { response.headers().add("Access-Control-Allow-Headers", "origin, content-type, accept"); } sendHttpResponse(context, request, response); } if (request.getMethod() != GET) { sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // TODO: send browserified page if (request.getUri().equals("/")) { request.setUri("/index.html"); } InputStream stream = null; /* if (request.getUri().startsWith("/resources/")) { File file = new File( plugin.getResourceDir(), request.getUri().substring("/resources/".length()) ); stream = new FileInputStream(file); } else { */ stream = this.getClass().getClassLoader().getResourceAsStream("www" + request.getUri()); if (stream == null) { sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); return; } ByteBufOutputStream out = new ByteBufOutputStream(Unpooled.buffer()); copyStream(stream, out); stream.close(); out.close(); ByteBuf buffer = out.buffer(); if (request.getUri().equals("/index.html")) { String page = buffer.toString(CharsetUtil.UTF_8); page = page.replaceAll("%SERVERPORT%", Integer.toString(this.port)); buffer.release(); buffer = Unpooled.wrappedBuffer(page.getBytes(CharsetUtil.UTF_8)); } FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer); if (request.getUri().startsWith("/resources/")) { response.headers().add("Access-Control-Allow-Origin", "*"); } String ext = request.getUri().substring(request.getUri().lastIndexOf('.') + 1); String type = mimeTypes.containsKey(ext) ? mimeTypes.get(ext) : "text/plain"; if (type.startsWith("text/")) { type += "; charset=UTF-8"; } response.headers().set(CONTENT_TYPE, type); setContentLength(response, response.content().readableBytes()); sendHttpResponse(context, request, response); }
From source file:deathcap.wsmc.web.HTTPHandler.java
License:Apache License
public void sendHttpResponse(ChannelHandlerContext context, FullHttpRequest request, FullHttpResponse response) {// w w w .j ava 2 s . c o m if (response.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(response.getStatus().toString(), CharsetUtil.UTF_8); response.content().writeBytes(buf); buf.release(); } setContentLength(response, response.content().readableBytes()); ChannelFuture future = context.channel().writeAndFlush(response); if (!isKeepAlive(request) || response.getStatus().code() != 200) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:deathcap.wsmc.web.WebSocketHandler.java
License:Apache License
@Override protected void messageReceived(final ChannelHandlerContext ctx, BinaryWebSocketFrame msg) throws Exception { // channelRead if (firstMessage) { firstMessage = false;/*from ww w .j a v a2s. co m*/ this.webThread.getChannelGroup().add(ctx.channel()); } MinecraftThread minecraft = minecraftThreads.get(ctx.channel().remoteAddress().toString()); if (minecraft == null) { this.setupInitialConnection(ctx, msg); return; } final ByteBuf buf = msg.content(); if (verbose) logger.info("ws received " + buf.readableBytes() + " bytes: " + HexDumper.hexByteBuf(buf)); byte bytes[] = new byte[buf.readableBytes()]; buf.readBytes(bytes); // read packet id type for filtering int id = DefinedPacket.readVarInt(Unpooled.copiedBuffer(bytes)); // TODO: avoid copying (but need to reply with id in buffer) if (!this.filter.isAllowed(id)) { logger.info("FILTERED PACKET: " + id); return; } final ByteBuf reply = Unpooled.wrappedBuffer(bytes).retain(); if (verbose) logger.info( "id " + id + " stripped " + reply.readableBytes() + " reply=" + HexDumper.hexByteBuf(reply)); final MinecraftThread mc = minecraft; // forward MC to WS try { final ChannelFuture f = mc.clientHandler.minecraftClientHandler.ctx.writeAndFlush(reply); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { try { assert f == channelFuture; if (verbose) logger.info("forwarded WS -> MC, " + reply.readableBytes() + " bytes"); reply.release(); } catch (RejectedExecutionException ex) { // TODO } } }); } catch (RejectedExecutionException ex) { //TODO mc.clientHandler.minecraftClientHandler.close(ctx, ) } }
From source file:discord4j.voice.PacketTransformer.java
License:Open Source License
@Nullable byte[] nextReceive(ByteBuf packet) { byte[] header = new byte[RTP_HEADER_LENGTH]; packet.getBytes(0, header);//from w w w. jav a2 s . com int audioOffset = RTP_HEADER_LENGTH + (4 * (byte) (header[0] & 0x0F)); byte[] encrypted = new byte[packet.readableBytes() - audioOffset]; packet.getBytes(audioOffset, encrypted); packet.release(); byte[] decrypted = boxer.open(encrypted, getNonce(header)); if (decrypted == null) { return null; } byte[] newPacket = new byte[RTP_HEADER_LENGTH + decrypted.length]; System.arraycopy(header, 0, newPacket, 0, RTP_HEADER_LENGTH); System.arraycopy(decrypted, 0, newPacket, audioOffset, decrypted.length); return newPacket; }
From source file:divconq.api.internal.ClientHandler.java
License:Open Source License
public void send(Message msg) { Logger.debug("Sending message: " + msg); try {/*from w w w . ja va 2s.c o m*/ if (this.chan != null) { if (this.info.getKind() == ConnectorKind.WebSocket) this.chan.writeAndFlush(new TextWebSocketFrame(msg.toString())); else { DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, this.info.getPath()); req.headers().set(Names.HOST, this.info.getHost()); req.headers().set(Names.USER_AGENT, "DivConq HyperAPI Client 1.0"); req.headers().set(Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); req.headers().set(Names.CONTENT_ENCODING, "UTF-8"); req.headers().set(Names.CONTENT_TYPE, "application/json; charset=utf-8"); req.headers().set(Names.COOKIE, ClientCookieEncoder.encode(this.cookies.values())); // TODO make more efficient - UTF8 encode directly to buffer ByteBuf buf = Unpooled.copiedBuffer(msg.toString(), CharsetUtil.UTF_8); int clen = buf.readableBytes(); req.content().writeBytes(buf); buf.release(); // Add 'Content-Length' header only for a keep-alive connection. req.headers().set(Names.CONTENT_LENGTH, clen); this.chan.writeAndFlush(req); } } } catch (Exception x) { Logger.error("Send HTTP Message error: " + x); } }