List of usage examples for io.netty.channel ChannelOption ALLOCATOR
ChannelOption ALLOCATOR
To view the source code for io.netty.channel ChannelOption ALLOCATOR.
Click Source Link
From source file:com.tesora.dve.tools.libmy.AsyncExample.java
License:Open Source License
public static void main(String[] args) throws Exception { final String mysqlHost = "localhost"; final int mysqlPort = 3307; final String username = "root"; final String password = "password"; final boolean isClearText = true; final InetSocketAddress serverAddress = new InetSocketAddress(mysqlHost, mysqlPort); final MyBackendDecoder.CharsetDecodeHelper charsetHelper = constructCharsetDecodeHelper(); final SimpleCredentials cred = constructCredentials(username, password, isClearText); final JavaCharsetCatalog javaCharsetCatalog = constructJavaCharsetCatalog(); final MysqlClientAuthenticationHandler authHandler = new MysqlClientAuthenticationHandler(cred, ClientCapabilities.DEFAULT_PSITE_CAPABILITIES, javaCharsetCatalog, new AtomicReference<Charset>()); final NioEventLoopGroup connectionEventGroup = new NioEventLoopGroup(1); final Bootstrap mysqlBootstrap = new Bootstrap(); mysqlBootstrap // .group(inboundChannel.eventLoop()) .channel(NioSocketChannel.class).group(connectionEventGroup) .option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT) .handler(new ChannelInitializer<Channel>() { @Override//from www . j av a2s . c o m protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(authHandler).addLast(MyBackendDecoder.class.getSimpleName(), new MyBackendDecoder(charsetHelper)).addLast(new ChannelDuplexHandler() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { System.out.println("WRITE:" + msg); super.write(ctx, msg, promise); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof MyFieldPktResponse) { final MyFieldPktResponse myFieldPktResponse = (MyFieldPktResponse) msg; System.out.println("COLUMN: " + myFieldPktResponse.getOrig_column() + "," + myFieldPktResponse.getColumn_type()); } else if (msg instanceof MyTextResultRow) { final StringBuilder builder = new StringBuilder(); builder.append("ROW:"); final MyTextResultRow textRow = (MyTextResultRow) msg; for (int i = 0; i < textRow.size(); i++) { builder.append('\t'); builder.append(textRow.getString(i)); } System.out.println(builder.toString()); } super.channelRead(ctx, msg); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); System.out.println("CLOSE. "); } }); } }); final ChannelFuture connectFut = mysqlBootstrap.connect(serverAddress); connectFut.sync(); System.out.println("Waiting to finish authenticate handshake"); authHandler.assertAuthenticated();//don't write a request until you know the login is complete. System.out.println("Connected, and authenticated, getting channel to write requests"); final Channel chan = connectFut.channel(); System.out.println("Sending two pipelined requests without blocking for first response."); chan.write(MSPComQueryRequestMessage.newMessage("show databases", CharsetUtil.UTF_8)); chan.write( MSPComQueryRequestMessage.newMessage("select * from information_schema.tables", CharsetUtil.UTF_8)); chan.flush();//NOTE: nothing is sent until this is called. Use writeAndFlush if you want it to go out immediately. System.out.println("Sleeping 5 sec so all results come back"); //normally you would sync to responses here. TimeUnit.SECONDS.sleep(5); System.out.println("Closing socket."); chan.writeAndFlush(MSPComQuitRequestMessage.newMessage());//send friendly hangup message. Probably correct to also wait for server close or an OK packet. chan.close(); chan.closeFuture().sync(); System.out.println("Exiting."); System.exit(0); }
From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcServer.java
License:Apache License
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyServerConfig.getServerWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override/* w w w .j a v a 2 s . c o m*/ public Thread newThread(Runnable r) { return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet()); } }); ServerBootstrap childHandler = // this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector) .channel(NioServerSocketChannel.class) // .option(ChannelOption.SO_BACKLOG, 1024) // .option(ChannelOption.SO_REUSEADDR, true) // .option(ChannelOption.SO_KEEPALIVE, false) // .childOption(ChannelOption.TCP_NODELAY, true) // .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()) // .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()) // .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( // defaultEventExecutorGroup, // new NettyEncoder(), // new NettyDecoder(), // new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), // new NettyConnectManageHandler(), // new NettyServerHandler()); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } if (this.channelEventListener != null) { this.nettyEventExecutor.start(); } this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRpcServer.this.scanResponseTable(); } catch (Exception e) { LOGGER.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); LOGGER.info("Rpc server [port:{}] start success", port); }
From source file:com.turn.ttorrent.client.io.PeerClient.java
License:Apache License
public void start() throws Exception { bootstrap = new Bootstrap(); bootstrap.group(environment.getEventService()); bootstrap.channel(environment.getEventLoopType().getClientChannelType()); // SocketAddress address = environment.getLocalPeerListenAddress(); // if (address != null) bootstrap.localAddress(address); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.TCP_NODELAY, true); // bootstrap.option(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES)); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) TimeUnit.SECONDS.toMillis(10)); // TODO: Derive from PieceHandler.DEFAULT_BLOCK_SIZE // bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024); // bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); }
From source file:com.turn.ttorrent.client.io.PeerServer.java
License:Apache License
/** * Create and start a new listening service for our torrents, reporting * with our peer ID on the given address. * * <p>/* w w w. java2s. co m*/ * This binds to the first available port in the client port range * PORT_RANGE_START to PORT_RANGE_END. * </p> */ public void start() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(environment.getEventService()); bootstrap.channel(environment.getEventLoopType().getServerChannelType()); bootstrap.option(ChannelOption.SO_BACKLOG, 128); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new PeerServerHandshakeHandler(torrents)); } }); bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // bootstrap.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES)); // TODO: Derive from PieceHandler.DEFAULT_BLOCK_SIZE // bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024); // bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); SocketAddress address = environment.getLocalPeerListenAddress(); if (address != null) { future = bootstrap.bind(address).sync(); } else { BIND: { Exception x = new IOException("No available port for the BitTorrent client!"); for (int i = PORT_RANGE_START; i <= PORT_RANGE_END; i++) { try { future = bootstrap.bind(i).sync(); break BIND; } catch (InterruptedException e) { throw e; } catch (Exception e) { x = e; } } throw new IOException("Failed to find an address to bind in range [" + PORT_RANGE_START + "," + PORT_RANGE_END + "]", x); } } }
From source file:com.util.MyServer.java
License:Apache License
/** * Start the server/* w w w .j a v a 2 s . c o m*/ */ public void start() throws IllegalArgumentException { ServerBindListener serverBindListener = new ServerBindListener(logger, this); bootStrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); /* * if no binding address is specified, bind "Wildcard" IP address. * https://docs.oracle.com/javase/7/docs/api/java/net/InetSocketAddress.html */ if (bindAddress.length == 0) { bootStrap.bind(serverPort).addListener(serverBindListener); } else { /* * Looping through binding address array, bind it one by one. */ for (String address : bindAddress) { bootStrap.bind(address, serverPort).addListener(serverBindListener); } } }
From source file:com.wolfbe.configcenter.remoting.netty.NettyRemotingServer.java
License:Apache License
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyServerConfig.getServerWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override/* w w w.ja va 2 s .c o m*/ public Thread newThread(Runnable r) { return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet()); } }); ServerBootstrap childHandler = // this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector) .channel(NioServerSocketChannel.class) // .option(ChannelOption.SO_BACKLOG, 1024) // .option(ChannelOption.SO_REUSEADDR, true) // .option(ChannelOption.SO_KEEPALIVE, false) // .childOption(ChannelOption.TCP_NODELAY, true) // .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()) // .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()) // .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(defaultEventExecutorGroup, // new NettyEncoder(), // new NettyDecoder(), // new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), // new NettyConnetManageHandler(), // new NettyServerHandler()); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } if (this.channelEventListener != null) { this.nettyEventExecuter.start(); } this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingServer.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
From source file:com.xx_dev.apn.proxy.ApnProxyServer.java
License:Apache License
public void start() { int bossThreadCount = ApnProxyConfig.getConfig().getBossThreadCount(); int workerThreadCount = ApnProxyConfig.getConfig().getWorkerThreadCount(); int port = ApnProxyConfig.getConfig().getPort(); LoggerUtil.info(logger, "ApnProxy Server Listen on: " + port); ServerBootstrap serverBootStrap = new ServerBootstrap(); serverBootStrap.childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT); bossGroup = new NioEventLoopGroup(bossThreadCount); workerGroup = new NioEventLoopGroup(workerThreadCount); try {/*from w w w. j a v a 2 s . c o m*/ serverBootStrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(port) .childHandler(new ApnProxyServerChannelInitializer()); serverBootStrap.bind().sync().channel().closeFuture().sync(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { logger.error("showdown the server"); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentForwardHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception { final Channel uaChannel = uaChannelCtx.channel(); final ApnProxyRemote apnProxyRemote = uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get() .getRemote();//from w w w .j a va 2 s . c o m if (msg instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) msg; Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr()); if (remoteChannel != null && remoteChannel.isActive()) { LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Use old remote channel"); HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote); remoteChannel.writeAndFlush(request); } else { LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Create new remote channel"); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new ApnProxyRemoteForwardChannelInitializer(uaChannel, this)); // set local address if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) { bootstrap.localAddress(new InetSocketAddress( (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0)); } ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort()); remoteChannel = remoteConnectFuture.channel(); remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel); remoteConnectFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote)); for (HttpContent hc : httpContentBuffer) { future.channel().writeAndFlush(hc); if (hc instanceof LastHttpContent) { future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().read(); } } }); } } httpContentBuffer.clear(); } else { LoggerUtil.error(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Remote channel create fail"); // send error response String errorMsg = "remote connect to " + uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote() .getRemoteAddr() + " fail"; HttpMessage errorResponseMsg = HttpErrorUtil .buildHttpErrorMessage(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorMsg); uaChannel.writeAndFlush(errorResponseMsg); httpContentBuffer.clear(); future.channel().close(); } } }); } ReferenceCountUtil.release(msg); } else { Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr()); HttpContent hc = ((HttpContent) msg); //hc.retain(); //HttpContent _hc = hc.copy(); if (remoteChannel != null && remoteChannel.isActive()) { remoteChannel.writeAndFlush(hc); if (hc instanceof LastHttpContent) { remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().read(); } } }); } } else { httpContentBuffer.add(hc); } } }
From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentTunnelHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception { if (msg instanceof HttpRequest) { final HttpRequest httpRequest = (HttpRequest) msg; //Channel uaChannel = uaChannelCtx.channel(); // connect remote Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new ApnProxyTunnelChannelInitializer(uaChannelCtx.channel())); final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel() .attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote(); // set local address if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) { bootstrap.localAddress(new InetSocketAddress( (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0)); }//from ww w. j a v a2 s .c om bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future1) throws Exception { if (future1.isSuccess()) { if (apnProxyRemote.isAppleyRemoteRule()) { uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME); uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME); // add relay handler uaChannelCtx.pipeline() .addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel())); future1.channel() .writeAndFlush(Unpooled.copiedBuffer( constructConnectRequestForProxy(httpRequest, apnProxyRemote), CharsetUtil.UTF_8)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { if (!future2.channel().config() .getOption(ChannelOption.AUTO_READ)) { future2.channel().read(); } } }); } else { HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established")); uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { // remove handlers uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME); uaChannelCtx.pipeline() .remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME); // add relay handler uaChannelCtx.pipeline() .addLast(new ApnProxyRelayHandler( "UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel())); } }); } } else { if (uaChannelCtx.channel().isActive()) { uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); } ReferenceCountUtil.release(msg); }
From source file:com.xx_dev.apn.proxy.expriment.HttpServer.java
License:Apache License
public static void main(String[] args) { ServerBootstrap serverBootStrap = new ServerBootstrap(); serverBootStrap.childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT); try {/*from w w w. j av a2s. c o m*/ serverBootStrap.group(new NioEventLoopGroup(1), new NioEventLoopGroup(2)) .channel(NioServerSocketChannel.class).localAddress(5000) .childHandler(new HttpServerChannelInitializer()); serverBootStrap.bind().sync().channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { } }