List of usage examples for io.netty.channel ChannelPipeline addLast
ChannelPipeline addLast(EventExecutorGroup group, ChannelHandler... handlers);
From source file:chapter10.WebSocketServer.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from w ww.j av a 2 s .c o m ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("http-codec", new HttpServerCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); pipeline.addLast("handler", new WebSocketServerHandler()); } }); Channel ch = b.bind(port).sync().channel(); System.out.println("Web socket server started at port " + port + '.'); System.out.println("Open your browser and navigate to http://localhost:" + port + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:ChatClient.ChatClientInitializer.java
@Override protected void initChannel(SocketChannel c) throws Exception { ChannelPipeline pipeline = c.pipeline(); pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader()))); pipeline.addLast("encoder", new ObjectEncoder()); pipeline.addLast("handler", new ChatClientHandler()); }
From source file:ChatServer.ChatServerInitializer.java
@Override protected void initChannel(SocketChannel c) throws Exception { ChannelPipeline pipeline = c.pipeline(); pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader()))); pipeline.addLast("encoder", new ObjectEncoder()); pipeline.addLast("handler", new ChatServerHandler()); }
From source file:code.google.nfs.rpc.netty.client.NettyClientFactory.java
License:Apache License
protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key) throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .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"))); if (connectTimeout < 1000) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); } else {//from w w w . j av a 2 s. c o m bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); } final NettyClientHandler handler = new NettyClientHandler(this, key); bootstrap.handler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast("decoder", new NettyProtocolDecoder()); pipeline.addLast("encoder", new NettyProtocolEncoder()); pipeline.addLast("handler", handler); } }); ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort)).sync(); 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()); } NettyClient client = new NettyClient(future, key, connectTimeout); handler.setClient(client); return client; }
From source file:code.google.nfs.rpc.netty.server.NettyServer.java
License:Apache License
public void start(int listenPort, final ExecutorService threadPool) throws Exception { if (!startFlag.compareAndSet(false, true)) { return;/* www. j a v a2 s .c o m*/ } bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast("decoder", new NettyProtocolDecoder()); pipeline.addLast("encoder", new NettyProtocolEncoder()); pipeline.addLast("handler", new NettyServerHandler(threadPool)); } }); bootstrap.bind(new InetSocketAddress(listenPort)).sync(); LOGGER.warn("Server started,listen at: " + listenPort); }
From source file:com.addthis.hydra.query.web.QueryServerInitializer.java
License:Apache License
@Override protected void initChannel(final SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (log.isTraceEnabled()) { log.trace("New socket connection {}", ch); ch.closeFuture().addListener(new ChannelFutureListener() { @Override// w ww .j a v a 2s . c om public void operationComplete(ChannelFuture future) throws Exception { log.trace("channel closed {}", ch); } }); } pipeline.addLast("decoder", new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize)); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength)); // compression is neat, but a little buggy // pipeline.addLast(ImmediateEventExecutor.INSTANCE, "compressor", new HttpContentCompressor()); pipeline.addLast("query", httpQueryHandler); }
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/* ww w. j a v a2 s . c om*/ 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 w ww . ja v a 2s. c om*/ 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.allanbank.mongodb.netty.NettyChannelInit.java
License:Apache License
/** * {@inheritDoc}/*from w w w. j a v a2 s.com*/ * <p> * Overridden to initialize the channel's processing pipeline. * </p> */ @Override public void initChannel(final SocketChannel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); // Make sure we know when the connection gets closed. ch.closeFuture().addListener(new NettyCloseListener(myResponseListener)); SSLEngine engine = null; final SocketFactory socketFactory = myClientConfig.getSocketFactory(); if (socketFactory instanceof SslEngineFactory) { final SslEngineFactory factory = (SslEngineFactory) socketFactory; engine = factory.createSSLEngine(); } else if (socketFactory instanceof SSLSocketFactory) { engine = createVanillaEngine((SSLSocketFactory) socketFactory); } if (engine != null) { engine.setUseClientMode(true); final SslHandler handler = new SslHandler(engine, false /* startTLS */); pipeline.addLast("ssl", handler); if (socketFactory instanceof SocketConnectionListener) { handler.handshakeFuture().addListener(new NettyTlsConnectionCompletedListener( (SocketConnectionListener) socketFactory, engine, ch)); } } // Read side. pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(myClientConfig.getReadTimeout(), TimeUnit.MILLISECONDS)); pipeline.addLast("bufToMessageHandler", new ByteToMessageDecoder(myDecoderCache)); pipeline.addLast("replyHandler", new NettyReplyHandler(myResponseListener)); }
From source file:com.andrewkroh.cisco.xmlservices.HttpClientInitializer.java
License:Apache License
@Override public void initChannel(SocketChannel ch) throws Exception { // Create a default pipeline implementation. ChannelPipeline p = ch.pipeline(); // Create a logger for debugging purposes: p.addLast("log", new LoggingHandler(LogLevel.INFO)); // Adds codec for handling HTTP messages: p.addLast("codec", new HttpClientCodec()); // Add decompresser for GZIP'ed messages: p.addLast("inflater", new HttpContentDecompressor()); // Add automatic handling of "chunked" HTTP messages: p.addLast("aggregator", new HttpObjectAggregator(1048576)); // Finally add our handler: p.addLast("handler", handler); }