@Override public ChannelFuture sendPushMessage(ChannelHandlerContext ctx, ByteBuf mesg) { final ByteBuf newBuff = ctx.alloc().buffer(); newBuff.ensureWritable(SSE_PREAMBLE.length()); newBuff.writeCharSequence(SSE_PREAMBLE, Charsets.UTF_8); newBuff.ensureWritable(mesg.writableBytes()); newBuff.writeBytes(mesg); newBuff.ensureWritable(SSE_TERMINATION.length()); newBuff.writeCharSequence(SSE_TERMINATION, Charsets.UTF_8); mesg.release(); return ctx.channel().writeAndFlush(newBuff); }
private void handleHttp2(Channel ch) { HandlerHolder<HttpHandlers> holder = httpHandlerMgr.chooseHandler(ch.eventLoop()); if (holder == null) { ch.close(); return; } VertxHttp2ConnectionHandler<Http2ServerConnection> handler = buildHttp2ConnectionHandler(holder); ch.pipeline().addLast("handler", handler); configureHttp2(ch.pipeline()); }
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (!acceptForeignIp) { if (!((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().isLoopbackAddress()) { ByteBuf cb = Unpooled.wrappedBuffer((QosConstants.BR_STR + "Foreign Ip Not Permitted." + QosConstants.BR_STR).getBytes()); ctx.writeAndFlush(cb).addListener(ChannelFutureListener.CLOSE); } } } }
/** * Closes the internal datagram channel used for sending and receiving DNS messages, and clears all DNS resource * records from the cache. Attempting to send a DNS query or to resolve a domain name will fail once this method * has been called. */ @Override public void close() { if (ch.isOpen()) { ch.close(); } }
private void fireException0(Throwable cause) { // Only fire the exception if the channel is open and registered // if not the pipeline is not setup and so it would hit the tail // of the pipeline. // See https://github.com/netty/netty/issues/1517 if (fireExceptionListener != null && channel.isRegistered()) { channel.pipeline().fireExceptionCaught(cause); } } }
public int start(final int port, final ChannelInitializer<? extends Channel> pipelineFactory) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(group) .channel(NioServerSocketChannel.class) .childHandler(pipelineFactory); try { future = bootstrap.bind(port).sync(); SocketAddress socketAddress = future.channel().localAddress(); return ((InetSocketAddress) socketAddress).getPort(); } catch (InterruptedException e) { throw new MocoException(e); } }
public void start() throws Exception { final EchoServerHandler serverHandler = new EchoServerHandler(); EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(serverHandler); } }); ChannelFuture f = b.bind().sync(); System.out.println(EchoServer.class.getName() + " started and listening for connections on " + f.channel().localAddress()); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } } }
@Override protected ListenableFuture<ClientHttpResponse> executeInternal(final HttpHeaders headers) throws IOException { final SettableListenableFuture<ClientHttpResponse> responseFuture = new SettableListenableFuture<>(); ChannelFutureListener connectionListener = future -> { if (future.isSuccess()) { Channel channel = future.channel(); channel.pipeline().addLast(new RequestExecuteHandler(responseFuture)); FullHttpRequest nettyRequest = createFullHttpRequest(headers); channel.writeAndFlush(nettyRequest); } else { responseFuture.setException(future.cause()); } }; this.bootstrap.connect(this.uri.getHost(), getPort(this.uri)).addListener(connectionListener); return responseFuture; }
public final void run(final String host, final int port, final ChannelHandler pipelineFactory) { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .remoteAddress(host, port) .option(ChannelOption.TCP_NODELAY, true) .handler(pipelineFactory); try { Channel channel = bootstrap.connect().sync().channel(); ChannelFuture future = channel.closeFuture().sync(); future.addListener(ChannelFutureListener.CLOSE); } catch (InterruptedException e) { throw new MocoException(e); } finally { group.shutdownGracefully(); } } }
public final void sendHttpResponse(HttpRequest req, ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, status); resp.headers().add("Content-Length", "0"); final boolean closeConn = ((status != OK) || (! HttpUtil.isKeepAlive(req))); if (closeConn) { resp.headers().add(HttpHeaderNames.CONNECTION, "Close"); } final ChannelFuture cf = ctx.channel().writeAndFlush(resp); if (closeConn) { cf.addListener(ChannelFutureListener.CLOSE); } }
/** * Start Sharding-Proxy. * * @param port port * @throws InterruptedException interrupted exception */ public void start(final int port) throws InterruptedException { try { ServerBootstrap bootstrap = new ServerBootstrap(); bossGroup = createEventLoopGroup(); if (bossGroup instanceof EpollEventLoopGroup) { groupsEpoll(bootstrap); } else { groupsNio(bootstrap); } ChannelFuture future = bootstrap.bind(port).sync(); if (GLOBAL_REGISTRY.getShardingProperties().<Boolean>getValue(ShardingPropertiesConstant.PROXY_BACKEND_USE_NIO)) { BackendNettyClientManager.getInstance().start(workerGroup); } future.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); backendExecutorContext.getExecuteEngine().close(); if (GLOBAL_REGISTRY.getShardingProperties().<Boolean>getValue(ShardingPropertiesConstant.PROXY_BACKEND_USE_NIO)) { BackendNettyClientManager.getInstance().stop(); } } }
@Test public void testInvalidServerResponse() throws Exception { ServerBootstrap bootstrap = createH2Server((dec, enc) -> new Http2EventAdapter() { @Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception { enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("xyz"), 0, false, ctx.newPromise()); ctx.flush(); } }); ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync(); try { Context ctx = vertx.getOrCreateContext(); ctx.runOnContext(v -> { client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", onFailure(err -> { assertOnIOContext(ctx); if (err instanceof NumberFormatException) { testComplete(); } })) .connectionHandler(conn -> conn.exceptionHandler(err -> fail())) .end(); }); await(); } finally { s.channel().close().sync(); } }
@Override @SuppressWarnings("unchecked") public void channelRead(ChannelHandlerContext ctx, Object msg) { final Channel child = (Channel) msg; child.pipeline().addLast(childHandler); setChannelOptions(child, childOptions, logger); for (Entry<AttributeKey<?>, Object> e: childAttrs) { child.attr((AttributeKey<Object>) e.getKey()).set(e.getValue()); } try { childGroup.register(child).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { forceClose(child, future.cause()); } } }); } catch (Throwable t) { forceClose(child, t); } }
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // Add a handler that just catches the Http2Exception that we fire to tell the codec to gracefully shutdown a connection. // We want to catch it so that it doesn't get logged by the DefaultChannelPipeline as if it was a _real_ // exception. ChannelPipeline parentPipeline = ctx.channel().parent().pipeline(); String handlerName = "h2_exception_swallow_handler"; if (parentPipeline.get(handlerName) == null) { parentPipeline.addLast(handlerName, SWALLOW_EXCEPTION_HANDLER); } }
public void reconfigure(InetSocketAddress addr) { Channel oldChannel = parentChannel; try { LOG.info("binding to port {}", addr); parentChannel = bootstrap.bind(addr).syncUninterruptibly().channel(); // Port changes after bind() if the original port was 0, update // localAddress to get the real port. localAddress = (InetSocketAddress) parentChannel.localAddress(); LOG.info("bound to port " + getLocalPort()); } catch (Exception e) { LOG.error("Error while reconfiguring", e); } finally { oldChannel.close(); } }
@Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { final byte[] bytes = new byte[msg.readableBytes()]; msg.readBytes(bytes); final RawMessage raw = new RawMessage(bytes, (InetSocketAddress) ctx.channel().remoteAddress()); input.processRawMessage(raw); }
public void stop() throws IOException, InterruptedException { LOG.info("Stopping LlapOutputFormatService"); if (listeningChannelFuture != null) { listeningChannelFuture.channel().close().sync(); listeningChannelFuture = null; } else { LOG.warn("LlapOutputFormatService does not appear to have a listening port to close."); } eventLoopGroup.shutdownGracefully(1, WAIT_TIME, TimeUnit.SECONDS).sync(); }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { RequestState state = ctx.channel().attr(ATTR_REQ_STATE).get(); if (msg instanceof HttpResponse) { state.response = (HttpResponse) msg; state.responseBodySize = 0; } if (msg instanceof HttpContent) { state.responseBodySize += ((HttpContent) msg).content().readableBytes(); } super.write(ctx, msg, promise); } }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { if (maxConnections > 0) { int currentCount = connections.getAndIncrement(); if (currentCount + 1 > maxConnections) { LOG.warn("Throttling incoming connection as above configured max connections threshold of " + maxConnections); Channel channel = ctx.channel(); channel.attr(ATTR_CH_THROTTLED).set(Boolean.TRUE); CurrentPassport.fromChannel(channel).add(PassportState.SERVER_CH_THROTTLING); channel.close(); ctx.pipeline().fireUserEventTriggered(CONNECTION_THROTTLED_EVENT); } } super.channelActive(ctx); }