List of usage examples for io.netty.channel ChannelHandlerAdapter ChannelHandlerAdapter
ChannelHandlerAdapter
From source file:NettyBootSpeedTest.java
@Test public void testBoot() throws InterruptedException { long start = System.currentTimeMillis(); Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class); bootstrap.group(new NioEventLoopGroup()); bootstrap.handler(new ChannelHandlerAdapter() { });//ww w. ja v a 2 s. com long mid = System.currentTimeMillis(); bootstrap.bind(10000).await(); bootstrap.connect("localhost", 10000).await(); long end = System.currentTimeMillis(); System.out.println("Setup took " + (mid - start) + " ms"); System.out.println("Boot took " + (end - start) + " ms"); }
From source file:at.yawk.accordion.netty.NettyConnector.java
License:Mozilla Public License
@Override public Optional<Connection> connect(SocketAddress address) { // TODO find a non-hacky method to close channels Collection<Channel> registeredChannels = Collections.synchronizedList(new ArrayList<>()); EventLoopGroup workerGroup = new NioEventLoopGroup() { @Override// w w w.j av a 2 s . c om public ChannelFuture register(Channel channel, ChannelPromise promise) { registeredChannels.add(channel); return super.register(channel, promise); } }; AtomicReference<Connection> connectionRef = new AtomicReference<>(); // init Bootstrap bootstrap = new Bootstrap().group(workerGroup).handler(new ChannelHandlerAdapter() { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { NettyConnection connection = new NettyConnection(ctx.channel()); connectionRef.set(connection); connection.init(); } }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true); try { // connect ChannelFuture connectFuture = bootstrap.connect(address); // wait for connection connectFuture.sync(); return Optional.of(connectionRef.get()); } catch (Exception e) { // shut down workers workerGroup.shutdownGracefully(); // kill channels registeredChannels.forEach(NettyConnection::close); return Optional.empty(); } }
From source file:com.baidu.rigel.biplatform.ma.file.client.service.impl.FileServerClient.java
License:Open Source License
/** * ?/*w w w . ja va 2 s .co m*/ * * @param server * ?? * @param port * ?? * @param request * * @return */ public Response doRequest(String server, int port, final Request request) { EventLoopGroup work = new NioEventLoopGroup(1); String message = null; try { final Response rs = new Response(ResponseStatus.FAIL, "failed", null); ChannelHandlerAdapter requestHandler = new ChannelHandlerAdapter() { /** * {@inheritDoc} */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { logger.info("successfully connect to file server"); ctx.write(request); ctx.flush(); } /** * {@inheritDoc} */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { logger.info("successfuly recieve message from file server {}", msg); Response tmpRs = (Response) msg; rs.setDatas(tmpRs.getDatas()); rs.setMessage(tmpRs.getMessage()); rs.setStatus(tmpRs.getStatus()); ctx.close(); } /** * {@inheritDoc} */ @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } /** * {@inheritDoc} */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error(cause.getMessage()); rs.setMessage(cause.getMessage()); rs.setStatus(ResponseStatus.FAIL); ctx.close(); } }; Bootstrap strap = new Bootstrap(); strap.group(work).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel chl) throws Exception { // ?? chl.pipeline().addLast(new ObjectDecoder( ClassResolvers.cacheDisabled(requestHandler.getClass().getClassLoader()))); chl.pipeline().addLast(new ObjectEncoder()); chl.pipeline().addLast(requestHandler); } }); long begin = System.currentTimeMillis(); logger.debug("Begin invoke do file operation request ... ..."); ChannelFuture future = strap.connect(server, port); future.channel().closeFuture().sync(); logger.debug( "Success execute request option cost time: " + (System.currentTimeMillis() - begin) + "ms"); return rs; } catch (InterruptedException e) { logger.error(e.getMessage(), e); message = e.getMessage(); } finally { work.shutdownGracefully(); } Response rs = new Response(ResponseStatus.FAIL, message, null); return rs; }
From source file:com.dinstone.netty.Client.java
License:Apache License
public static void main(String[] args) throws IOException, InterruptedException { Bootstrap b = new Bootstrap(); b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override/*from ww w .j av a 2s . c o m*/ protected void initChannel(NioSocketChannel ch) throws Exception { ch.pipeline().addLast("dd", new ChannelHandlerAdapter() { /** * {@inheritDoc} * * @see io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel.ChannelHandlerContext, * java.lang.Throwable) */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("error: "); cause.printStackTrace(); } }); } }); b.connect("localhost", 8090).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().write(Unpooled.buffer().writeBytes("123".getBytes())); future.channel().flush(); } } }); }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStoreTest.java
License:Open Source License
@Test(expected = ConnectException.class, timeout = 30000) public void timeoutShouldWork_connect() throws Exception { ServerSocketChannel server = startServer(new ChannelHandlerAdapter() { });/*from ww w . j av a 2 s .com*/ int serverPort = server.localAddress().getPort(); closeServerChannel(server); Credentials credentials = newCredentials(); HttpBlobStore blobStore = new HttpBlobStore(new URI("http://localhost:" + serverPort), 5, credentials); blobStore.get("key", new ByteArrayOutputStream()); fail("Exception expected"); }
From source file:io.grpc.netty.ProtocolNegotiatorsTest.java
License:Apache License
@Test public void waitUntilActiveHandler_handlerAdded() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final WaitUntilActiveHandler handler = new WaitUntilActiveHandler(new ChannelHandlerAdapter() { @Override//from w w w . j a va2 s. c om public void handlerAdded(ChannelHandlerContext ctx) throws Exception { assertTrue(ctx.channel().isActive()); latch.countDown(); super.handlerAdded(ctx); } }); ChannelHandler lateAddingHandler = new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addLast(handler); ctx.pipeline().fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT); // do not propagate channelActive(). } }; LocalAddress addr = new LocalAddress("local"); ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(lateAddingHandler).group(group) .register(); chan = cf.channel(); ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class) .childHandler(new ChannelHandlerAdapter() { }).group(group).bind(addr); server = sf.channel(); sf.sync(); assertEquals(1, latch.getCount()); chan.connect(addr).sync(); assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); assertNull(chan.pipeline().context(WaitUntilActiveHandler.class)); }
From source file:io.grpc.netty.ProtocolNegotiatorsTest.java
License:Apache License
@Test public void waitUntilActiveHandler_channelActive() throws Exception { final CountDownLatch latch = new CountDownLatch(1); WaitUntilActiveHandler handler = new WaitUntilActiveHandler(new ChannelHandlerAdapter() { @Override/*from w ww.j ava 2 s . com*/ public void handlerAdded(ChannelHandlerContext ctx) throws Exception { assertTrue(ctx.channel().isActive()); latch.countDown(); super.handlerAdded(ctx); } }); LocalAddress addr = new LocalAddress("local"); ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register(); chan = cf.channel(); ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class) .childHandler(new ChannelHandlerAdapter() { }).group(group).bind(addr); server = sf.channel(); sf.sync(); assertEquals(1, latch.getCount()); chan.connect(addr).sync(); chan.pipeline().fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT); assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); assertNull(chan.pipeline().context(WaitUntilActiveHandler.class)); }
From source file:io.grpc.netty.WriteBufferingAndExceptionHandlerTest.java
License:Apache License
@Test public void connectionFailuresPropagated() throws Exception { WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler( new ChannelHandlerAdapter() { });//ww w.j ava 2s .co m ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register(); chan = cf.channel(); cf.sync(); // Write before connect. In the event connect fails, the pipeline is torn down and the handler // won't be able to fail the writes with the correct exception. ChannelFuture wf = chan.writeAndFlush(new Object()); chan.connect(new LocalAddress("bogus")); try { wf.sync(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(ConnectException.class); assertThat(e).hasMessageThat().contains("connection refused"); } }
From source file:io.grpc.netty.WriteBufferingAndExceptionHandlerTest.java
License:Apache License
@Test public void channelInactiveFailuresPropagated() throws Exception { WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler( new ChannelHandlerAdapter() { });//from w w w. j a va 2 s . c o m LocalAddress addr = new LocalAddress("local"); ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register(); chan = cf.channel(); cf.sync(); ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class) .childHandler(new ChannelHandlerAdapter() { }).group(group).bind(addr); server = sf.channel(); sf.sync(); ChannelFuture wf = chan.writeAndFlush(new Object()); chan.connect(addr); chan.pipeline().fireChannelInactive(); try { wf.sync(); fail(); } catch (Exception e) { Status status = Status.fromThrowable(e); assertThat(status.getCode()).isEqualTo(Code.UNAVAILABLE); assertThat(status.getDescription()).contains("Connection closed while performing protocol negotiation"); } }
From source file:io.grpc.netty.WriteBufferingAndExceptionHandlerTest.java
License:Apache License
@Test public void channelCloseFailuresPropagated() throws Exception { WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler( new ChannelHandlerAdapter() { });/*w w w. j a v a 2 s. co m*/ LocalAddress addr = new LocalAddress("local"); ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register(); chan = cf.channel(); cf.sync(); ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class) .childHandler(new ChannelHandlerAdapter() { }).group(group).bind(addr); server = sf.channel(); sf.sync(); ChannelFuture wf = chan.writeAndFlush(new Object()); chan.connect(addr); chan.close(); try { wf.sync(); fail(); } catch (Exception e) { Status status = Status.fromThrowable(e); assertThat(status.getCode()).isEqualTo(Code.UNAVAILABLE); assertThat(status.getDescription()) .contains("Connection closing while performing protocol negotiation"); } }