List of usage examples for io.netty.buffer Unpooled EMPTY_BUFFER
ByteBuf EMPTY_BUFFER
To view the source code for io.netty.buffer Unpooled EMPTY_BUFFER.
Click Source Link
From source file:NettyInboundHttpTargetHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // System.out.println("Activating Chanel"); ctx.read();//from ww w . jav a2 s . c o m ctx.write(Unpooled.EMPTY_BUFFER); }
From source file:NettyHttpTransportSourceHandler.java
License:Apache License
/** * Closes the specified channel after all queued write requests are flushed. *///from ww w . j a v a2 s. c o m static void closeOnFlush(Channel ch) { if (ch.isActive()) { ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }
From source file:at.yawk.accordion.distributed.HeartbeatManager.java
License:Mozilla Public License
/** * Send a heartbeat to all connected servers and check if they are still online. *///from w ww .jav a2s . c o m private void beat() { connectionManager.getConnections().forEach(connection -> { // send heartbeat try { connectionManager.sendPacket(InternalProtocol.HEARTBEAT_BYTES, Stream.of(connection), Unpooled.EMPTY_BUFFER); } catch (Throwable t) { connectionManager.getLogger().error("Failed to send heartbeat to " + connection, t); } // check for timeout try { Object lastHeartbeatObj = connection.properties().get("lastHeartbeat"); // null if no hb packet was received yet and onConnected wasn't called for some reason. if (lastHeartbeatObj != null) { long timeSinceLastHeartbeat = System.currentTimeMillis() - (long) lastHeartbeatObj; if (timeSinceLastHeartbeat > TIMEOUT) { // timeout Log.info(connectionManager.getLogger(), () -> connection + " timed out (heartbeat)"); connection.disconnect(); } } } catch (Throwable t) { connectionManager.getLogger().error("Failed to confirm heartbeat for " + connection, t); } }); }
From source file:brave.netty.http.TestHttpHandler.java
License:Apache License
private boolean writeResponse(HttpResponseStatus responseStatus, String content, ChannelHandlerContext ctx) { if (StringUtil.isNullOrEmpty(content)) { content = Unpooled.EMPTY_BUFFER.toString(); }/* w ww .ja v a2 s.com*/ // Decide whether to close the connection or not. boolean keepAlive = isKeepAlive(httpRequest); if (responseStatus == null) { responseStatus = httpRequest.getDecoderResult().isSuccess() ? OK : BAD_REQUEST; } // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(CONNECTION, Values.KEEP_ALIVE); } // Write the response. ctx.write(response); return keepAlive; }
From source file:bzh.ygu.fun.chitchat.HttpChitChatServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);// w w w . j av a2s .c om } String uri = request.uri(); HttpMethod method = request.method(); Root root = Root.getInstance(); buf.setLength(0); contentBuf.setLength(0); if (method == HttpMethod.POST) { if (uri.equals("/chitchat")) { currentAction = "Add"; } } if (method == HttpMethod.GET) { if (uri.startsWith(LATEST)) { latestFromWho = decode(uri.substring(LATEST_SIZE)); currentAction = "Latest"; Message m = root.getLatest(latestFromWho); if (m != null) { //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715} buf.append(m.toJSON()); } } if (uri.startsWith(THREADCALL)) { currentAction = "Thread"; String threadId = uri.substring(THREADCALL_SIZE); MessageThread mt = root.getMessageThread(threadId); if (mt != null) { //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715} buf.append(mt.toJSON()); } } if (uri.startsWith(SEARCH)) { String stringToSearch = decode(uri.substring(SEARCH_SIZE)); currentAction = "search"; List<Message> lm = root.search(stringToSearch); //[{"author":"Loki", "text":"I have an army !", "thread":3, //"createdAt":1404736639710}, {"author":"Iron Man", "text":"We have a Hulk !", // "thread":3, "createdAt":1404736639715}] buf.append("["); if (!lm.isEmpty()) { Iterator<Message> it = lm.iterator(); Message m = it.next(); buf.append(m.toJSON()); while (it.hasNext()) { m = it.next(); buf.append(", "); buf.append(m.toJSON()); } } buf.append("]"); } } } if (msg instanceof HttpContent) { Root root = Root.getInstance(); HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { contentBuf.append(content.toString(CharsetUtil.UTF_8)); } if (msg instanceof LastHttpContent) { // buf.append("END OF CONTENT\r\n"); if (currentAction.equals("Add")) { addMessageFromContent(contentBuf.toString(), root); currentAction = "None"; } LastHttpContent trailer = (LastHttpContent) msg; if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:cc.agentx.client.net.nio.Socks5Handler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, SocksRequest request) throws Exception { switch (request.protocolVersion()) { case SOCKS4a: log.warn("\tBad Handshake! (protocol version not supported: 4)"); ctx.write(new SocksInitResponse(SocksAuthScheme.UNKNOWN)); if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }//ww w . java2s .c o m break; case SOCKS5: switch (request.requestType()) { case INIT: ctx.pipeline().addFirst(new SocksCmdRequestDecoder()); ctx.write(new SocksInitResponse(SocksAuthScheme.NO_AUTH)); break; case AUTH: ctx.pipeline().addFirst(new SocksCmdRequestDecoder()); ctx.write(new SocksAuthResponse(SocksAuthStatus.SUCCESS)); break; case CMD: if (((SocksCmdRequest) request).cmdType() == SocksCmdType.CONNECT) { ctx.pipeline().addLast(new XConnectHandler()); ctx.pipeline().remove(this); ctx.fireChannelRead(request); } else { ctx.close(); log.warn("\tBad Handshake! (command not support: {})", ((SocksCmdRequest) request).cmdType()); } break; case UNKNOWN: log.warn("\tBad Handshake! (unknown request type)"); } break; case UNKNOWN: log.warn("\tBad Handshake! (protocol version not support: {}", request.protocolVersion()); ctx.close(); break; } }
From source file:cc.agentx.client.net.nio.Socks5Handler.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) { throwable.printStackTrace();/* w ww.j a va 2 s .c o m*/ if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }
From source file:cc.agentx.client.net.nio.XConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { boolean proxyMode = isAgentXNeeded(request.host()); log.info("\tClient -> Proxy \tTarget {}:{} [{}]", request.host(), request.port(), proxyMode ? "AGENTX" : "DIRECT"); Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override// w w w . ja va2 s.com public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType())) .addListener(channelFuture -> { ByteBuf byteBuf = Unpooled.buffer(); request.encodeAsByteBuf(byteBuf); if (byteBuf.hasArray()) { byte[] xRequestBytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, xRequestBytes); if (proxyMode) { // handshaking to remote proxy xRequestBytes = requestWrapper.wrap(xRequestBytes); outboundChannel.writeAndFlush(Unpooled.wrappedBuffer( exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes))); } // task handover ReferenceCountUtil.retain(request); // auto-release? a trap? ctx.pipeline().remove(XConnectHandler.this); outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(), proxyMode ? wrapper : rawWrapper, false)); ctx.pipeline().addLast(new XRelayHandler(outboundChannel, proxyMode ? wrapper : rawWrapper, true)); } }); } else { ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }); String host = request.host(); int port = request.port(); if (host.equals(config.getConsoleDomain())) { host = "localhost"; port = config.getConsolePort(); } else if (proxyMode) { host = config.getServerHost(); port = config.getServerPort(); } // ping target bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.channel().writeAndFlush( new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }); }
From source file:cc.agentx.client.net.nio.XConnectHandler.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }/*from www .java 2 s . com*/ log.warn("\tBad Connection! ({})", cause.getMessage()); }
From source file:cc.agentx.client.net.nio.XRelayHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER); }