Java Code Examples for io.netty.channel.ChannelInitializer

The following examples show how to use io.netty.channel.ChannelInitializer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@BeforeClass
public static void init() {
    // Configure a test server
    group = new DefaultEventLoopGroup();
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group)
            .channel(LocalServerChannel.class)
            .childHandler(new ChannelInitializer<LocalChannel>() {
                @Override
                public void initChannel(LocalChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) {
                            // Discard
                            ReferenceCountUtil.release(msg);
                        }
                    });
                }
            });

    localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress();
}
 
Example 2
Source Project: WeEvent   Source File: TcpBroker.java    License: Apache License 2.0 6 votes vote down vote up
private Channel tcpServer(int port) throws Exception {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(this.bossGroup, this.workerGroup)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline channelPipeline = socketChannel.pipeline();
                    channelPipeline.addFirst("idle", new IdleStateHandler(
                            0,
                            0,
                            weEventConfig.getKeepAlive()));

                    //channelPipeline.addLast("ssl", getSslHandler(sslContext, socketChannel.alloc()));
                    channelPipeline.addLast("decoder", new MqttDecoder());
                    channelPipeline.addLast("encoder", MqttEncoder.INSTANCE);
                    channelPipeline.addLast("broker", new TcpHandler(protocolProcess));
                }
            });
    return serverBootstrap.bind(port).sync().channel();
}
 
Example 3
private Bootstrap initClientBootstrap() {
    Bootstrap b = new Bootstrap();
    eventLoopGroup = new NioEventLoopGroup();
    b.group(eventLoopGroup)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ClusterClientConfigManager.getConnectTimeout())
        .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                clientHandler = new TokenClientHandler(currentState, disconnectCallback);

                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2));
                pipeline.addLast(new NettyResponseDecoder());
                pipeline.addLast(new LengthFieldPrepender(2));
                pipeline.addLast(new NettyRequestEncoder());
                pipeline.addLast(clientHandler);
            }
        });

    return b;
}
 
Example 4
Source Project: netty-4.1.22   Source File: OcspTest.java    License: Apache License 2.0 6 votes vote down vote up
private static ChannelHandler newServerHandler(final SslContext context,
        final byte[] response, final ChannelHandler handler) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
                engine.setOcspResponse(response);
            }

            pipeline.addLast(sslHandler);

            if (handler != null) {
                pipeline.addLast(handler);
            }
        }
    };
}
 
Example 5
Source Project: arcusplatform   Source File: VideoPreviewServerModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
   bind(BridgeServerConfig.class);
   bind(PreviewConfig.class);
   bind(BridgeServerTlsContext.class).to(BridgeServerTlsContextImpl.class);
   bind(BridgeServerTrustManagerFactory.class).to(NullTrustManagerFactoryImpl.class);
   bind(ChannelInboundHandler.class).toProvider(BaseWebSocketServerHandlerProvider.class);
   bind(new TypeLiteral<ChannelInitializer<SocketChannel>>(){}).to(HttpRequestInitializer.class);
   bind(Authenticator.class).to(ShiroAuthenticator.class);
   bind(SessionFactory.class).to(DefaultSessionFactoryImpl.class);
   bind(SessionRegistry.class).to(DefaultSessionRegistryImpl.class);
   bind(RequestMatcher.class).annotatedWith(Names.named("WebSocketUpgradeMatcher")).to(NeverMatcher.class);
   bind(RequestAuthorizer.class).annotatedWith(Names.named("SessionAuthorizer")).to(SessionAuth.class);
   bind(IrisNettyAuthorizationContextLoader.class).to(SubscriberAuthorizationContextLoader.class);

   // No Session Listeners
   Multibinder<SessionListener> slBindings = Multibinder.newSetBinder(binder(), SessionListener.class);

   // Bind Http Handlers
   Multibinder<RequestHandler> rhBindings = Multibinder.newSetBinder(binder(), RequestHandler.class);
   rhBindings.addBinding().to(RootRedirect.class);
   rhBindings.addBinding().to(IndexPage.class);
   rhBindings.addBinding().to(CheckPage.class);
   rhBindings.addBinding().to(PreviewHandler.class);
}
 
Example 6
Source Project: arcusplatform   Source File: ServerRunner.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
public ServerRunner(
      BridgeServerConfig serverConfig,
      InetSocketAddress socketBindAddress,
      ChannelInitializer<SocketChannel> channelInitializer,
      @Named("bossGroup") EventLoopGroup bossGroup,
      @Named("workerGroup") EventLoopGroup workerGroup,
      @Named("tcpChannelOptions") Map<ChannelOption<?>, Object> childChannelOptions,
      @Named("tcpParentChannelOptions") Map<ChannelOption<?>, Object> parentChannelOptions,
      @Named("bridgeEventLoopProvider") BridgeServerEventLoopProvider eventLoopProvider
) {
   this.serverConfig = serverConfig;
   this.socketBindAddress = socketBindAddress;
   this.channelInitializer = channelInitializer;
   this.bossGroup = bossGroup;
   this.workerGroup = workerGroup;
   this.childChannelOptions = childChannelOptions;
   this.parentChannelOptions = parentChannelOptions;
   this.eventLoopProvider = eventLoopProvider;
}
 
Example 7
Source Project: arcusplatform   Source File: ClusterAwareServerRunner.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
public ClusterAwareServerRunner(
      BridgeServerConfig serverConfig,
      InetSocketAddress socketBindAddress,
      ChannelInitializer<SocketChannel> channelInitializer,
      @Named("bossGroup") EventLoopGroup bossGroup,
      @Named("workerGroup") EventLoopGroup workerGroup,
      @Named("tcpChannelOptions") Map<ChannelOption<?>, Object> childChannelOptions,
      @Named("tcpParentChannelOptions") Map<ChannelOption<?>, Object> parentChannelOptions,
      @Named("bridgeEventLoopProvider") BridgeServerEventLoopProvider eventLoopProvider
) {
   super(
         serverConfig,
         socketBindAddress,
         channelInitializer,
         bossGroup,
         workerGroup,
         childChannelOptions,
         parentChannelOptions,
         eventLoopProvider
   );
}
 
Example 8
Source Project: arcusplatform   Source File: ServerModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
   // TODO this should be in an auth module
   bind(BridgeServerConfig.class);
   bind(BridgeServerTlsContext.class).to(BridgeServerTlsContextImpl.class);
   if(AUTHZ_LOADER_NONE.equals(algorithm)) {
      bind(BridgeServerTrustManagerFactory.class).to(NullTrustManagerFactoryImpl.class);
   }
   else {
      throw new IllegalArgumentException("Unrecognized authz loader class");
   }
   bind(new TypeLiteral<ChannelInitializer<SocketChannel>>(){})
      .to(Bridge10ChannelInitializer.class);

   bind(ServerRunner.class).asEagerSingleton();
}
 
Example 9
Source Project: netty-4.1.22   Source File: ByteEchoPeerBase.java    License: Apache License 2.0 6 votes vote down vote up
public void run() throws Exception {
    final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
            connectFactory, NioUdtProvider.BYTE_PROVIDER);
    try {
        final Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(connectGroup)
                .channelFactory(NioUdtProvider.BYTE_RENDEZVOUS)
                .handler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    protected void initChannel(UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new LoggingHandler(LogLevel.INFO),
                                new ByteEchoPeerHandler(messageSize));
                    }
                });
        final ChannelFuture future = bootstrap.connect(peerAddress, myAddress).sync();
        future.channel().closeFuture().sync();
    } finally {
        connectGroup.shutdownGracefully();
    }
}
 
Example 10
Source Project: netty-4.1.22   Source File: RxtxClient.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 11
Source Project: netty-4.1.22   Source File: StompClient.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new StompSubframeDecoder());
                pipeline.addLast("encoder", new StompSubframeEncoder());
                pipeline.addLast("aggregator", new StompSubframeAggregator(1048576));
                pipeline.addLast("handler", new StompClientHandler());
            }
        });

        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 12
Source Project: wind-im   Source File: WsServer.java    License: Apache License 2.0 5 votes vote down vote up
public WsServer() {
	executor = new SimpleExecutor<Command, CommandResponse>();
	loadExecutor(executor);
	// 负责对外连接线程
	parentGroup = new NioEventLoopGroup();
	// 负责对内分发业务的线程
	childGroup = new NioEventLoopGroup();
	bootstrap = new ServerBootstrap();
	bootstrap.group(parentGroup, childGroup);
	bootstrap.channel(NioServerSocketChannel.class);
	bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			// 30秒空闲时间设置
			ch.pipeline().addLast(new IdleStateHandler(30, 0, 60));
			// HttpServerCodec:将请求和应答消息解码为HTTP消息
			ch.pipeline().addLast(new HttpServerCodec());
			// 针对大文件上传时,把 HttpMessage 和 HttpContent 聚合成一个
			// FullHttpRequest,并定义可以接受的数据大小64M(可以支持params+multipart)
			ch.pipeline().addLast(new HttpObjectAggregator(64 * 1024));
			// 针对大文件下发,分块写数据
			ch.pipeline().addLast(new ChunkedWriteHandler());
			// WebSocket 访问地址
			// ch.pipeline().addLast(new WebSocketServerProtocolHandler("/akaxin/ws"));
			// 自定义handler
			ch.pipeline().addLast(new WsServerHandler(executor));
		}
	});

}
 
Example 13
Source Project: journalkeeper   Source File: DefaultTransportServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected ChannelHandler newChannelHandlerPipeline() {
    final CommandDispatcher commandDispatcher = new DefaultCommandDispatcher(requestBarrier, requestHandler, responseHandler);
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline()
                    .addLast(new NettyDecoder(codec))
                    .addLast(new NettyEncoder(codec))
                    .addLast(new TransportEventHandler(requestBarrier, transportEventBus))
                    .addLast(new ExceptionChannelHandler(exceptionHandler, requestBarrier))
                    .addLast(new CommandInvocation(commandDispatcher));
        }
    };
}
 
Example 14
Source Project: journalkeeper   Source File: DefaultTransportClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected ChannelHandler newChannelHandlerPipeline() {
    final CommandDispatcher commandDispatcher = new DefaultCommandDispatcher(requestBarrier, requestHandler, responseHandler);
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel channel) {
            channel.pipeline()
                    .addLast(new NettyDecoder(codec))
                    .addLast(new NettyEncoder(codec))
                    .addLast(new ClientConnectionHandler())
                    .addLast(new TransportEventHandler(requestBarrier, transportEventBus))
                    .addLast(new CommandInvocation(commandDispatcher));
        }
    };
}
 
Example 15
Source Project: netty-4.1.22   Source File: ProxyHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void test() throws Exception {
    final FailureTestHandler testHandler = new FailureTestHandler();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.resolver(NoopAddressResolverGroup.INSTANCE);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientHandlers);
            p.addLast(new LineBasedFrameDecoder(64));
            p.addLast(testHandler);
        }
    });

    boolean finished = b.connect(destination).channel().closeFuture().await(10, TimeUnit.SECONDS);
    finished &= testHandler.latch.await(10, TimeUnit.SECONDS);

    logger.debug("Recorded exceptions: {}", testHandler.exceptions);

    assertProxyHandlers(false);

    assertThat(testHandler.exceptions.size(), is(1));
    Throwable e = testHandler.exceptions.poll();
    assertThat(e, is(instanceOf(ProxyConnectException.class)));
    assertThat(String.valueOf(e), containsString(expectedMessage));
    assertThat(finished, is(true));
}
 
Example 16
Source Project: PowerTunnel   Source File: ProxyToServerConnection.java    License: MIT License 5 votes vote down vote up
@Override
protected Future<?> execute() {
    Bootstrap cb = new Bootstrap()
            .group(proxyServer.getProxyToServerWorkerFor(transportProtocol))
            .resolver(remoteAddressResolver);

    switch (transportProtocol) {
        case TCP:
            LOG.debug("Connecting to server with TCP");
            cb.channelFactory(NioSocketChannel::new);
            break;
        case UDT:
            LOG.debug("Connecting to server with UDT");
            cb.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
                    .option(ChannelOption.SO_REUSEADDR, true);
            break;
        default:
            throw new UnknownTransportProtocolException(transportProtocol);
    }

    cb.handler(new ChannelInitializer<Channel>() {
        protected void initChannel(Channel ch) {
            initChannelPipeline(ch.pipeline(), initialRequest);
        }
    });
    cb.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            proxyServer.getConnectTimeout());

    if (localAddress != null) {
        return cb.connect(remoteAddress, localAddress);
    } else {
        return cb.connect(remoteAddress);
    }
}
 
Example 17
Source Project: besu   Source File: NettyConnectionInitializer.java    License: Apache License 2.0 5 votes vote down vote up
/** @return a channel initializer for inbound connections */
private ChannelInitializer<SocketChannel> inboundChannelInitializer() {
  return new ChannelInitializer<SocketChannel>() {
    @Override
    protected void initChannel(final SocketChannel ch) {
      final CompletableFuture<PeerConnection> connectionFuture = new CompletableFuture<>();
      connectionFuture.thenAccept(
          connection -> connectSubscribers.forEach(c -> c.onConnect(connection)));

      ch.pipeline()
          .addLast(
              new TimeoutHandler<>(
                  connectionFuture::isDone,
                  TIMEOUT_SECONDS,
                  () ->
                      connectionFuture.completeExceptionally(
                          new TimeoutException(
                              "Timed out waiting to fully establish incoming connection"))),
              new HandshakeHandlerInbound(
                  nodeKey,
                  config.getSupportedProtocols(),
                  localNode,
                  connectionFuture,
                  eventDispatcher,
                  metricsSystem));
    }
  };
}
 
Example 18
Source Project: fastjgame   Source File: OuterConnectorHandler.java    License: Apache License 2.0 5 votes vote down vote up
public OuterConnectorHandler(HostAndPort remoteAddress,
                             ChannelInitializer<SocketChannel> initializer,
                             NettyThreadManager nettyThreadManager,
                             Promise<Session> connectPromise) {
    this.remoteAddress = remoteAddress;
    this.initializer = initializer;
    this.nettyThreadManager = nettyThreadManager;
    this._connectPromise = connectPromise;
}
 
Example 19
Source Project: fastjgame   Source File: ConnectRemoteRequest.java    License: Apache License 2.0 5 votes vote down vote up
public ConnectRemoteRequest(String sessionId,
                            HostAndPort remoteAddress,
                            SocketSessionConfig config,
                            ChannelInitializer<SocketChannel> initializer,
                            NetContext netContext,
                            Promise<Session> connectPromise) {
    this.sessionId = sessionId;
    this.remoteAddress = remoteAddress;
    this.config = config;
    this.initializer = initializer;
    this.netContext = netContext;
    this.connectPromise = connectPromise;
}
 
Example 20
Source Project: fastjgame   Source File: ConnectorManager.java    License: Apache License 2.0 5 votes vote down vote up
public void connect(final ConnectRemoteRequest request) {
    final String sessionId = request.getSessionId();
    final HostAndPort remoteAddress = request.getRemoteAddress();
    final SocketSessionConfig config = request.getConfig();
    final ChannelInitializer<SocketChannel> initializer = request.getInitializer();
    final NetContext netContext = request.getNetContext();
    final Promise<Session> connectPromise = request.getConnectPromise();

    Session existSession = sessionRegistry.getSession(sessionId);
    if (existSession != null) {
        connectPromise.tryFailure(new IOException("session " + sessionId + " already registered"));
        return;
    }

    final SocketSessionImp session = new SocketSessionImp(netContext, sessionId, config,
            netManagerWrapper, this);

    if (config.isAutoReconnect()) {
        // 异步建立连接
        session.pipeline().addLast(new OuterConnectorHandler(remoteAddress, initializer, nettyThreadManager, connectPromise));
    } else {
        ChannelFuture channelFuture = nettyThreadManager.connectAsyn(remoteAddress,
                config.sndBuffer(),
                config.rcvBuffer(),
                config.connectTimeoutMs(),
                initializer);

        // 异步建立连接
        session.pipeline().addLast(new InnerConnectorHandler(channelFuture, connectPromise));
    }
}
 
Example 21
Source Project: dubbo-2.6.5   Source File: NettyClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    final NettyClientHandler nettyClientHandler = new NettyClientHandler(getUrl(), this);
    bootstrap = new Bootstrap();
    bootstrap.group(nioEventLoopGroup)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            //.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout())
            .channel(NioSocketChannel.class);

    if (getConnectTimeout() < 3000) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
    } else {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeout());
    }

    bootstrap.handler(new ChannelInitializer() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                    .addLast("decoder", adapter.getDecoder())
                    .addLast("encoder", adapter.getEncoder())
                    .addLast("handler", nettyClientHandler);
        }
    });
}
 
Example 22
Source Project: dubbo-2.6.5   Source File: NettyServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
    protected void doOpen() throws Throwable {
        bootstrap = new ServerBootstrap();

        bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
//        iothreads参数值,默认cpu线程数+1 小于32
        workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
                new DefaultThreadFactory("NettyServerWorker", true));

        final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
        channels = nettyServerHandler.getChannels();

        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
                .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                        ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                                .addLast("decoder", adapter.getDecoder())
                                .addLast("encoder", adapter.getEncoder())
                                .addLast("handler", nettyServerHandler);
                    }
                });
        // bind
        ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
        channelFuture.syncUninterruptibly();
        channel = channelFuture.channel();

    }
 
Example 23
Source Project: dubbo-2.6.5   Source File: Server.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * start server, bind port
 */
public void start() throws Throwable {
    if (!hasStarted.compareAndSet(false, true)) {
        return;
    }
    boss = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-boss", true));
    worker = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-worker", true));
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(boss, worker);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    serverBootstrap.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new QosProcessHandler(welcome, acceptForeignIp));
        }
    });
    try {
        serverBootstrap.bind(port).sync();
        logger.info("qos-server bind localhost:" + port);
    } catch (Throwable throwable) {
        logger.error("qos-server can not bind localhost:" + port, throwable);
        throw throwable;
    }
}
 
Example 24
Source Project: simple-rpc-framework   Source File: NettyClient.java    License: Apache License 2.0 5 votes vote down vote up
private ChannelHandler newChannelHandlerPipeline() {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel channel) {
            channel.pipeline()
                    .addLast(new ResponseDecoder())
                    .addLast(new RequestEncoder())
                    .addLast(new ResponseInvocation(inFlightRequests));
        }
    };
}
 
Example 25
Source Project: simple-rpc-framework   Source File: NettyServer.java    License: Apache License 2.0 5 votes vote down vote up
private ChannelHandler newChannelHandlerPipeline() {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel channel) {
            channel.pipeline()
                    .addLast(new RequestDecoder())
                    .addLast(new ResponseEncoder())
                    .addLast(new RequestInvocation(requestHandlerRegistry));
        }
    };
}
 
Example 26
Source Project: netty-4.1.22   Source File: ProxyHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void test() throws Exception {
    final long TIMEOUT = 2000;
    for (ChannelHandler h: clientHandlers) {
        if (h instanceof ProxyHandler) {
            ((ProxyHandler) h).setConnectTimeoutMillis(TIMEOUT);
        }
    }

    final FailureTestHandler testHandler = new FailureTestHandler();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.resolver(NoopAddressResolverGroup.INSTANCE);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientHandlers);
            p.addLast(new LineBasedFrameDecoder(64));
            p.addLast(testHandler);
        }
    });

    ChannelFuture cf = b.connect(DESTINATION).channel().closeFuture();
    boolean finished = cf.await(TIMEOUT * 2, TimeUnit.MILLISECONDS);
    finished &= testHandler.latch.await(TIMEOUT * 2, TimeUnit.MILLISECONDS);

    logger.debug("Recorded exceptions: {}", testHandler.exceptions);

    assertProxyHandlers(false);

    assertThat(testHandler.exceptions.size(), is(1));
    Throwable e = testHandler.exceptions.poll();
    assertThat(e, is(instanceOf(ProxyConnectException.class)));
    assertThat(String.valueOf(e), containsString("timeout"));
    assertThat(finished, is(true));
}
 
Example 27
Source Project: g4proxy   Source File: ProxyToServerConnection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
        protected Future<?> execute() {
            Bootstrap cb = new Bootstrap().group(proxyServer.getProxyToServerWorkerFor(transportProtocol));

            switch (transportProtocol) {
            case TCP:
                LOG.debug("Connecting to server with TCP");
                cb.channelFactory(new ChannelFactory<Channel>() {
                    @Override
                    public Channel newChannel() {
                        return new NioSocketChannel();
                    }
                });
                break;
            case UDT:
                LOG.debug("Connecting to server with UDT");
//                cb.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
//                        .option(ChannelOption.SO_REUSEADDR, true);
//                break;
                throw new UnsupportedOperationException("unsupport udt proxy portocal");
            default:
                throw new UnknownTransportProtocolException(transportProtocol);
            }

            cb.handler(new ChannelInitializer<Channel>() {
                protected void initChannel(Channel ch) throws Exception {
                    initChannelPipeline(ch.pipeline(), initialRequest);
                };
            });
            cb.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    proxyServer.getConnectTimeout());

            if (localAddress != null) {
                return cb.connect(remoteAddress, localAddress);
            } else {
                return cb.connect(remoteAddress);
            }
        }
 
Example 28
@Test
public void usedHttp2MultiplexCodec() throws Exception {
    final Http2MultiplexCodec http2Codec = new Http2MultiplexCodecBuilder(true, new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
        }
    }).build();
    UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() {
        @Override
        public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
            return new Http2ServerUpgradeCodec(http2Codec);
        }
    };
    http2ConnectionHandler = http2Codec;

    userEvents = new ArrayList<Object>();

    HttpServerCodec httpServerCodec = new HttpServerCodec();
    HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(httpServerCodec, upgradeCodecFactory);

    CleartextHttp2ServerUpgradeHandler handler = new CleartextHttp2ServerUpgradeHandler(
            httpServerCodec, upgradeHandler, http2Codec);
    channel = new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            userEvents.add(evt);
        }
    });

    assertFalse(channel.writeInbound(Http2CodecUtil.connectionPrefaceBuf()));

    ByteBuf settingsFrame = settingsFrameBuf();

    assertTrue(channel.writeInbound(settingsFrame));

    assertEquals(1, userEvents.size());
    assertTrue(userEvents.get(0) instanceof PriorKnowledgeUpgradeEvent);
}
 
Example 29
Source Project: netty-pubsub   Source File: TestHttp.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
	EventLoopGroup bossGroup = new NioEventLoopGroup();
	EventLoopGroup workerGroup = new NioEventLoopGroup();
	ServerBootstrap bootstrap = new ServerBootstrap();
	bootstrap.group(bossGroup, workerGroup)
	.option(ChannelOption.SO_BACKLOG, 1024)
	.channel(NioServerSocketChannel.class)
	.childHandler(new ChannelInitializer<SocketChannel>() {
 
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ch.pipeline().addLast("http-decoder",new HttpRequestDecoder());
			ch.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65535));//�������Ϣת����һ��
			ch.pipeline().addLast("http-encoder",new HttpResponseEncoder());
			ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());//���������������
			ch.pipeline().addLast("http-server",new HttpHandler());
		}
	});
	
	try {
		ChannelFuture future = bootstrap.bind(8888).sync();
		future.channel().closeFuture().sync();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}finally {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}
}
 
Example 30
Source Project: code   Source File: EchoClient.java    License: Apache License 2.0 5 votes vote down vote up
public void start(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            //1、创建 Bootstrap
            Bootstrap bootstrap = new Bootstrap();
            //2、指定 EventLoopGroup 以处理客户端事件;需要适用于 NIO 的实现
            bootstrap.group(group)
                    //3、适用于 NIO 传输的Channel 类型
                    .channel(NioSocketChannel.class)
                    //4、设置服务器的InetSocketAddress
                    .remoteAddress(new InetSocketAddress(host, port))
                    //5、在创建Channel时,向 ChannelPipeline中添加一个 EchoClientHandler实例
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            //6、连接到远程节点,阻塞等待直到连接完成
            ChannelFuture f = bootstrap.connect().sync();
            //7、阻塞,直到Channel 关闭
            f.channel().closeFuture().sync();
        } finally {
            //8、关闭线程池并且释放所有的资源
            group.shutdownGracefully().sync();
        }

    }