List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer
ChannelInitializer
From source file:code.google.nfs.rpc.netty4.client.Netty4ClientFactory.java
License:Apache License
protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key) throws Exception { final Netty4ClientHandler handler = new Netty4ClientHandler(this, key); EventLoopGroup group = new NioEventLoopGroup(1); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true"))) .option(ChannelOption.SO_REUSEADDR, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true"))) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout < 1000 ? 1000 : connectTimeout) .handler(new ChannelInitializer<SocketChannel>() { @Override//w w w . ja va 2s .c o m public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("decoder", new Netty4ProtocolDecoder()); ch.pipeline().addLast("encoder", new Netty4ProtocolEncoder()); ch.pipeline().addLast("handler", handler); } }); ChannelFuture future = b.connect(targetIP, targetPort); future.awaitUninterruptibly(connectTimeout); if (!future.isDone()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!"); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!"); } if (future.isCancelled()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!"); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!"); } if (!future.isSuccess()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause()); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause()); } Netty4Client client = new Netty4Client(future, key, connectTimeout); handler.setClient(client); return client; }
From source file:code.google.nfs.rpc.netty4.server.Netty4Server.java
License:Apache License
public void start(int listenPort, final ExecutorService ignore) throws Exception { if (!startFlag.compareAndSet(false, true)) { return;// w w w .j av a 2s . c o m } bossGroup = new NioEventLoopGroup(); ioGroup = new NioEventLoopGroup(); businessGroup = new DefaultEventExecutorGroup(businessThreads); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, ioGroup).channel(NioServerSocketChannel.class) .childOption(ChannelOption.TCP_NODELAY, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true"))) .childOption(ChannelOption.SO_REUSEADDR, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true"))) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("decoder", new Netty4ProtocolDecoder()); ch.pipeline().addLast("encoder", new Netty4ProtocolEncoder()); ch.pipeline().addLast(businessGroup, "handler", new Netty4ServerHandler()); } }); b.bind(listenPort).sync(); LOGGER.warn("Server started,listen at: " + listenPort + ", businessThreads is " + businessThreads); }
From source file:com.addthis.meshy.Meshy.java
License:Apache License
protected Meshy() { if (HOSTNAME != null) { uuid = HOSTNAME + "-" + Long.toHexString(System.currentTimeMillis() & 0xffffff); } else {/*from w w w . j av a 2 s .c o m*/ uuid = Long.toHexString(UUID.randomUUID().getMostSignificantBits()); } workerGroup = new NioEventLoopGroup(); clientBootstrap = new Bootstrap().option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000) .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK) .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK).channel(NioSocketChannel.class) .group(workerGroup).handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(final NioSocketChannel ch) throws Exception { ch.pipeline().addLast(new ChannelState(Meshy.this, ch)); } }); updateLastEventTime(); }
From source file:com.addthis.meshy.MeshyServer.java
License:Apache License
public MeshyServer(final int port, final File rootDir, @Nullable String[] netif, final MeshyServerGroup group) throws IOException { super();/*from w w w . j av a2 s .co m*/ this.group = group; this.rootDir = rootDir; this.filesystems = loadFileSystems(rootDir); this.serverPeers = new AtomicInteger(0); bossGroup = new NioEventLoopGroup(1); ServerBootstrap bootstrap = new ServerBootstrap() .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000) .option(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK) .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK) .channel(NioServerSocketChannel.class).group(bossGroup, workerGroup) .childHandler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(final NioSocketChannel ch) throws Exception { ch.pipeline().addLast(new ChannelState(MeshyServer.this, ch)); } }); /* bind to one or more interfaces, if supplied, otherwise all */ if ((netif == null) || (netif.length == 0)) { ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap.bind(new InetSocketAddress(port)) .syncUninterruptibly().channel(); serverLocal = serverChannel.localAddress(); } else { InetSocketAddress primaryServerLocal = null; for (String net : netif) { NetworkInterface nicif = NetworkInterface.getByName(net); if (nicif == null) { log.warn("missing speficied NIC: {}", net); continue; } for (InterfaceAddress addr : nicif.getInterfaceAddresses()) { InetAddress inAddr = addr.getAddress(); if (inAddr.getAddress().length != 4) { log.trace("skip non-ipV4 address: {}", inAddr); continue; } ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap .bind(new InetSocketAddress(inAddr, port)).syncUninterruptibly().channel(); if (primaryServerLocal != null) { log.info("server [{}-*] binding to extra address: {}", super.getUUID(), primaryServerLocal); } primaryServerLocal = serverChannel.localAddress(); } } if (primaryServerLocal == null) { throw new IllegalArgumentException("no valid interface / port specified"); } serverLocal = primaryServerLocal; } this.serverNetIf = NetworkInterface.getByInetAddress(serverLocal.getAddress()); this.serverPort = serverLocal.getPort(); if (serverNetIf != null) { serverUuid = super.getUUID() + "-" + serverPort + "-" + serverNetIf.getName(); } else { serverUuid = super.getUUID() + "-" + serverPort; } log.info("server [{}] on {} @ {}", getUUID(), serverLocal, rootDir); closeFuture = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); workerGroup.terminationFuture().addListener((Future<Object> workerFuture) -> { bossGroup.terminationFuture().addListener((Future<Object> bossFuture) -> { if (!workerFuture.isSuccess()) { closeFuture.tryFailure(workerFuture.cause()); } else if (!bossFuture.isSuccess()) { closeFuture.tryFailure(bossFuture.cause()); } else { closeFuture.trySuccess(null); } }); }); addMessageFileSystemPaths(); group.join(this); if (autoMesh) { startAutoMesh(serverPort, autoMeshTimeout); } }
From source file:com.ahanda.techops.noty.clientTest.Client.java
License:Apache License
public static void main(String[] args) throws Exception { if (args.length == 1) { System.setProperty("PINT.conf", args[0]); }/*from w w w .j a v a2s. com*/ if (System.getProperty("PINT.conf") == null) throw new IllegalArgumentException(); JsonNode config = null; Config cf = Config.getInstance(); cf.setupConfig(); String scheme = "http"; String host = cf.getHttpHost(); int port = cf.getHttpPort(); if (port == -1) { port = 8080; } if (!"http".equalsIgnoreCase(scheme)) { l.warn("Only HTTP is supported."); return; } // Configure SSL context if necessary. final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec()); // p.addLast( "decoder", new HttpResponseDecoder()); // p.addLast( "encoder", new HttpRequestEncoder()); // Remove the following line if you don't want automatic content decompression. // p.addLast(new HttpContentDecompressor()); // Uncomment the following line if you don't want to handle HttpContents. p.addLast(new HttpObjectAggregator(10485760)); p.addLast(new ClientHandler()); } }); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); ClientHandler client = new ClientHandler(); client.login(ch, ClientHandler.credential); // ClientHandler.pubEvent( ch, ClientHandler.event ); // Wait for the server to close the connection. ch.closeFuture().sync(); l.info("Closing Client side Connection !!!"); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); } }
From source file:com.alexkasko.netty.ftp.FtpServerTest.java
License:Apache License
@Test public void test() throws IOException, InterruptedException { final DefaultCommandExecutionTemplate defaultCommandExecutionTemplate = new DefaultCommandExecutionTemplate( new ConsoleReceiver()); EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from w w w .j a va2 s . c o m*/ protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipe = ch.pipeline(); pipe.addLast("decoder", new CrlfStringDecoder()); pipe.addLast("handler", new FtpServerHandler(defaultCommandExecutionTemplate)); } }); b.localAddress(2121).bind(); FTPClient client = new FTPClient(); // https://issues.apache.org/jira/browse/NET-493 client.setBufferSize(0); client.connect("127.0.0.1", 2121); assertEquals(230, client.user("anonymous")); // active assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE)); assertEquals("/", client.printWorkingDirectory()); assertTrue(client.changeWorkingDirectory("/foo")); assertEquals("/foo", client.printWorkingDirectory()); assertTrue(client.listFiles("/foo").length == 0); assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes()))); assertTrue(client.rename("bar", "baz")); // assertTrue(client.deleteFile("baz")); // passive assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE)); client.enterLocalPassiveMode(); assertEquals("/foo", client.printWorkingDirectory()); assertTrue(client.changeWorkingDirectory("/foo")); assertEquals("/foo", client.printWorkingDirectory()); //TODO make a virtual filesystem that would work with directory //assertTrue(client.listFiles("/foo").length==1); assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes()))); assertTrue(client.rename("bar", "baz")); // client.deleteFile("baz"); assertEquals(221, client.quit()); try { client.noop(); fail("Should throw exception"); } catch (IOException e) { //expected; } }
From source file:com.alexkasko.netty.ftp.StartServer.java
License:Apache License
public static void main(String... args) throws Exception { final DefaultCommandExecutionTemplate defaultCommandExecutionTemplate = new DefaultCommandExecutionTemplate( new ConsoleReceiver()); EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from www . j a va2 s .c o m*/ protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipe = ch.pipeline(); pipe.addLast("decoder", new CrlfStringDecoder()); pipe.addLast("handler", new FtpServerHandler(defaultCommandExecutionTemplate)); } }); b.localAddress(2121).bind().channel().closeFuture().sync(); }
From source file:com.alibaba.dubbo.qos.server.Server.java
License:Apache License
/** * start server, bind port/*from w w w.j ava 2 s .c om*/ */ 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; } }
From source file:com.alibaba.dubbo.remoting.transport.netty.NettyClient.java
License:Apache License
@Override protected void doOpen() throws Throwable { NettyHelper.setNettyLoggerFactory(); 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 (getTimeout() < 3000) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000); } else {// ww w . java 2 s . c o m bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout()); } bootstrap.handler(new ChannelInitializer() { 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); } }); }
From source file:com.alibaba.dubbo.remoting.transport.netty.NettyServer.java
License:Apache License
@Override protected void doOpen() throws Throwable { NettyHelper.setNettyLoggerFactory(); //netty4/*from w ww. j a v a 2 s . c o m*/ bootstrap = new ServerBootstrap(); //1? bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true)); // cpu*2 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) .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE) .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(); }