List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer
ChannelInitializer
From source file:com.jjzhk.Chapter13.file.FileServer.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from w w w . j av a 2 s . c o m ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() { /* * (non-Javadoc) * * @see * io.netty.channel.ChannelInitializer#initChannel(io * .netty.channel.Channel) */ public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(1024), new StringDecoder(CharsetUtil.UTF_8), new FileServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); System.out.println("Start file server at port : " + port); f.channel().closeFuture().sync(); } finally { // ? bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.jjzhk.Chapter14.netty.NettyClient.java
License:Apache License
public void connect(int port, String host) throws Exception { try {//from w w w .ja v a 2 s . c o m Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4)); ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder()); ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50)); ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler()); ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler()); } }); ChannelFuture future = b.connect(new InetSocketAddress(host, port), new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync(); future.channel().closeFuture().sync(); } finally { executor.execute(new Runnable() { public void run() { try { TimeUnit.SECONDS.sleep(1); try { connect(NettyConstant.PORT, NettyConstant.REMOTEIP); } catch (Exception e) { e.printStackTrace(); } } catch (InterruptedException e) { e.printStackTrace(); } } }); } }
From source file:com.jjzhk.Chapter14.netty.NettyServer.java
License:Apache License
public void bind() throws Exception { // ?NIO?/* ww w. ja v a 2 s . c o m*/ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws IOException { ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4)); ch.pipeline().addLast(new NettyMessageEncoder()); ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50)); ch.pipeline().addLast(new LoginAuthRespHandler()); ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler()); } }); // ???? b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync(); System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT)); }
From source file:com.JohnnyTests.NettySimpleChat.gui.NettyTCPClient.java
License:Apache License
public void startClient() throws Exception { // Log//from w w w. j a v a 2 s .co m Logger logger = Logger.getLogger(NettyTCPClient.class); group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("encoder", new StringEncoder()); ch.pipeline().addLast("decoder", new StringDecoder()); // and then business logic. if (handler != null) ch.pipeline().addLast("handler", handler); } }); ChannelFuture f = bootstrap.connect(host, port).sync(); ch = f.channel(); System.out.println("Connected!"); }
From source file:com.jroossien.boxx.util.protocol.TinyProtocol.java
License:Open Source License
private void createServerChannelHandler() { // Handle connected channels endInitProtocol = new ChannelInitializer<Channel>() { @Override/* ww w . j ava 2 s. c om*/ protected void initChannel(Channel channel) throws Exception { try { // This can take a while, so we need to stop the main thread from interfering synchronized (networkManagers) { // Stop injecting channels if (!closed) { injectChannelInternal(channel); } } } catch (Exception e) { plugin.getLogger().log(Level.SEVERE, "Cannot inject incomming channel " + channel, e); } } }; // This is executed before Minecraft's channel handler beginInitProtocol = new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { channel.pipeline().addLast(endInitProtocol); } }; serverChannelHandler = new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Channel channel = (Channel) msg; // Prepare to initialize ths channel channel.pipeline().addFirst(beginInitProtocol); ctx.fireChannelRead(msg); } }; }
From source file:com.juaby.labs.rpc.server.Rpc2Server.java
License:Apache License
public void start() { RpcThreadFactory threadName = new RpcThreadFactory("RPC-SVR-WORKER", false); int threads = Runtime.getRuntime().availableProcessors() * 2 + 1; bossGroup = new NioEventLoopGroup(threads, threadName); workerGroup = new NioEventLoopGroup(); try {/*w w w . j av a2 s . c o m*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } p.addLast( //output new Rpc2ServerEncoder(), //input new Rpc2ServerDecoder(ServiceConfig.MAX_OBJECT_SIZE), new Rpc2ServerHandler()); } }); // Bind and start to accept incoming connections. //b.bind(HOST, PORT).sync().channel().closeFuture().sync(); b.bind(host, port); } finally { } }
From source file:com.kevinherron.GatewayHook.java
@Override public void startup(LicenseState licenseState) { logger.info("startup()"); try {// w w w. j av a 2 s .com Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoop).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { logger.info("initChannel"); } }); bootstrap.connect("localhost", 1234).get(2, TimeUnit.SECONDS); } catch (Throwable t) { logger.error("failed getting un-gettable endpoints: {}", t.getMessage(), t); } }
From source file:com.khs.microservice.whirlpool.whirlpoolserver.WhirlpoolServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*w w w. j a v a 2 s. co m*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8)); p.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8)); p.addLast("aggregator", new HttpObjectAggregator(65536)); p.addLast("handler", new WhirlpoolServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); logger.info("Whirlpool Server started"); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { logger.info("Whirlpool Server shutdown started"); // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); logger.info("Whirlpool Server shutdown completed"); } }
From source file:com.khs.stockticker.StockTickerServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from w w w.j a v a 2s.co m ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("aggregator", new HttpObjectAggregator(65536)); p.addLast("handler", new StockTickerServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); logger.info("Ticket Symbol Server started"); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { logger.info("Ticket Symbol Server shutdown started"); // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); logger.info("Ticket Symbol Server shutdown completed"); } }
From source file:com.king.platform.net.http.netty.ChannelManager.java
License:Apache License
public ChannelManager(NioEventLoopGroup nioEventLoop, final HttpClientHandler httpClientHandler, Timer nettyTimer, TimeProvider timeProvider, ChannelPool channelPool, final ConfMap confMap, RootEventBus rootEventBus) {//from ww w . j av a 2s . c om this.eventLoopGroup = nioEventLoop; this.nettyTimer = nettyTimer; this.timeProvider = timeProvider; this.channelPool = channelPool; this.confMap = confMap; plainBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); plainBootstrap.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); addLoggingIfDesired(pipeline, confMap.get(ConfKeys.NETTY_TRACE_LOGS)); pipeline.addLast("http-codec", newHttpClientCodec()); pipeline.addLast("inflater", new HttpContentDecompressor()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); pipeline.addLast("httpClientHandler", httpClientHandler); } }); secureBootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventLoopGroup); secureBootstrap.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); SslInitializer sslInitializer = new SslInitializer( new SSLFactory(confMap.get(ConfKeys.SSL_ALLOW_ALL_CERTIFICATES)), confMap.get(ConfKeys.SSL_HANDSHAKE_TIMEOUT_MILLIS)); pipeline.addLast(SslInitializer.NAME, sslInitializer); addLoggingIfDesired(pipeline, confMap.get(ConfKeys.NETTY_TRACE_LOGS)); pipeline.addLast("http-codec", newHttpClientCodec()); pipeline.addLast("inflater", new HttpContentDecompressor()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); pipeline.addLast("httpClientHandler", httpClientHandler); } }); secureBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, confMap.get(ConfKeys.CONNECT_TIMEOUT_MILLIS)); plainBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, confMap.get(ConfKeys.CONNECT_TIMEOUT_MILLIS)); NettyChannelOptions nettyChannelOptions = confMap.get(ConfKeys.NETTY_CHANNEL_OPTIONS); for (ChannelOption channelOption : nettyChannelOptions.keys()) { plainBootstrap.option(channelOption, nettyChannelOptions.get(channelOption)); secureBootstrap.option(channelOption, nettyChannelOptions.get(channelOption)); } rootEventBus.subscribePermanently(Event.ERROR, new ErrorCallback()); rootEventBus.subscribePermanently(Event.COMPLETED, new CompletedCallback()); rootEventBus.subscribePermanently(Event.EXECUTE_REQUEST, new ExecuteRequestCallback()); }