Java Code Examples for io.netty.bootstrap.Bootstrap#option()
The following examples show how to use
io.netty.bootstrap.Bootstrap#option() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractNettyClient.java From sailfish-core with Apache License 2.0 | 6 votes |
@Override public void connect() throws Exception { Bootstrap cb = new Bootstrap(); cb.group(nioEventLoopGroup); cb.channel(NioSocketChannel.class); cb.option(ChannelOption.SO_REUSEADDR, true); cb.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); cb.handler(NOOP_CHANNEL_INITIALIZER); Channel localChannel = cb.connect(getHost(), getPort()) .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) .addListener(ChannelFutureListener.CLOSE_ON_FAILURE) .awaitUninterruptibly() .channel(); mainSession = createSession(localChannel); mainSession.withWriteLock(this::initChannel); mainSession.withWriteLock(this::initChannelCloseFuture); }
Example 2
Source File: JT809Server.java From jt809-tcp-server with MIT License | 6 votes |
/** * 从链路(客户端)引导入口 * @param group * @throws Exception */ private void runClient(EventLoopGroup group) throws Exception { String ip = clientConfig.getTcpIp(); Integer port = clientConfig.getTcpPort(); try { Bootstrap client = new Bootstrap(); client.group(group); client.channel(NioSocketChannel.class); client.option(ChannelOption.TCP_NODELAY, true); client.handler(jt809ClientChannelInit); ChannelFuture channelFuture = client.connect(ip, port).sync(); channelFuture.addListener(new GenericFutureListener() { @Override public void operationComplete(Future future) throws Exception { if (future.isSuccess()) { log.info("nettyClient run success,TCP-IP:{},TCP-PORT:{}",ip,port); clientChannel = channelFuture.channel(); } } }); }catch (Exception e){ log.error("nettyClient run fail"); e.printStackTrace(); } }
Example 3
Source File: NettyHttpClient.java From mpush with Apache License 2.0 | 6 votes |
@Override protected void doStart(Listener listener) throws Throwable { workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT)); b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_REUSEADDR, true); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000); b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("decoder", new HttpResponseDecoder()); ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength)); ch.pipeline().addLast("encoder", new HttpRequestEncoder()); ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this)); } }); timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64); listener.onSuccess(); }
Example 4
Source File: AbstractConfigurableExchangeChannelGroup.java From sailfish with Apache License 2.0 | 6 votes |
private Bootstrap newBootstrap() { Bootstrap boot = new Bootstrap(); boot.channel(NettyPlatformIndependent.channelClass()); boot.option(ChannelOption.TCP_NODELAY, true); // replace by heart beat boot.option(ChannelOption.SO_KEEPALIVE, false); // default is pooled direct // ByteBuf(io.netty.util.internal.PlatformDependent.DIRECT_BUFFER_PREFERRED) boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // 32kb(for massive long connections, See // http://www.infoq.com/cn/articles/netty-million-level-push-service-design-points) // 64kb(RocketMq remoting default value) boot.option(ChannelOption.SO_SNDBUF, 32 * 1024); boot.option(ChannelOption.SO_RCVBUF, 32 * 1024); // temporary settings, need more tests boot.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024)); //default is true, reduce thread context switching boot.option(ChannelOption.SINGLE_EVENTEXECUTOR_PER_GROUP, true); return boot; }
Example 5
Source File: NettyClientServerCommunicationSystemClientSide.java From library with Apache License 2.0 | 6 votes |
/** * Tulio Ribeiro Connect to specific replica and returns the ChannelFuture. * sessionClientToReplica is replaced with the new connection. Removed redundant * code. */ public synchronized ChannelFuture connectToReplica(int replicaId, SecretKeyFactory fac) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException { String str = this.clientId + ":" + replicaId; PBEKeySpec spec = TOMUtil.generateKeySpec(str.toCharArray()); SecretKey authKey = fac.generateSecret(spec); Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec); b.handler(getChannelInitializer()); ChannelFuture channelFuture = b.connect(controller.getRemoteAddress(replicaId)); NettyClientServerSession ncss = new NettyClientServerSession( channelFuture.channel(), replicaId); sessionClientToReplica.put(replicaId, ncss); return channelFuture; }
Example 6
Source File: NettyServerClient.java From PeonyFramwork with Apache License 2.0 | 6 votes |
public NettyServerClient(int serverType,int serverId, String host, int port) { this.serverType = serverType; this.serverId = serverId; this.address = new InetSocketAddress(host, port); netEventService = BeanHelper.getServiceBean(NetEventService.class); eventService = BeanHelper.getServiceBean(EventService.class); bootstrap = new Bootstrap(); // (1) bootstrap.group(eventLoopGroup); // (2) bootstrap.channel(NioSocketChannel.class); // (3) bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // (4) bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new DefaultNettyEncoder(), new DefaultNettyDecoder(), new NettyClientHandler() ); } }); }
Example 7
Source File: HttpClient.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
private HttpClient() { // Configure the client. group = new NioEventLoopGroup(); bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new HttpClientInitializer(mHttpClientListener)); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECTION_TIMEOUT_MILLIS); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_RCVBUF, 65536 * 3); // added in 2017-07-14 bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator( 65536 * 3 )); // added in 2017-07-14 }
Example 8
Source File: EpollETSocketConditionalWritabilityTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override protected void configure(ServerBootstrap bootstrap, Bootstrap bootstrap2, ByteBufAllocator allocator) { super.configure(bootstrap, bootstrap2, allocator); bootstrap.option(EpollChannelOption.EPOLL_MODE, EpollMode.EDGE_TRIGGERED) .childOption(EpollChannelOption.EPOLL_MODE, EpollMode.EDGE_TRIGGERED); bootstrap2.option(EpollChannelOption.EPOLL_MODE, EpollMode.EDGE_TRIGGERED); }
Example 9
Source File: RequestResponseCloseHandlerTest.java From servicetalk with Apache License 2.0 | 5 votes |
private SocketChannel connectClient(InetSocketAddress address) { EventLoopAwareNettyIoExecutor eventLoopAwareNettyIoExecutor = toEventLoopAwareNettyIoExecutor(C_CTX.ioExecutor()); EventLoop loop = eventLoopAwareNettyIoExecutor.eventLoopGroup().next(); Bootstrap bs = new Bootstrap(); bs.group(loop); bs.channel(socketChannel(loop, InetSocketAddress.class)); bs.handler(new ChannelInitializer() { @Override protected void initChannel(final Channel ch) { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) { LOGGER.debug("Client Evt: {}", evt.getClass().getSimpleName()); if (evt == ChannelInputShutdownEvent.INSTANCE) { clientInputShutdownLatch.countDown(); } else if (evt == ChannelInputShutdownReadComplete.INSTANCE) { clientInputShutdownReadCompleteLatch.countDown(); } else if (evt == ChannelOutputShutdownEvent.INSTANCE) { clientOutputShutdownLatch.countDown(); } release(evt); } }); } }); bs.option(AUTO_READ, true); bs.option(ALLOW_HALF_CLOSURE, true); bs.option(AUTO_CLOSE, false); return (SocketChannel) bs.connect(address).syncUninterruptibly().channel(); }
Example 10
Source File: EpollLTSocketReadPendingTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override protected void configure(ServerBootstrap bootstrap, Bootstrap bootstrap2, ByteBufAllocator allocator) { super.configure(bootstrap, bootstrap2, allocator); bootstrap.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED) .childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); bootstrap2.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); }
Example 11
Source File: BootstrapManager.java From brpc-java with Apache License 2.0 | 5 votes |
public Bootstrap createBooStrap(String serviceName, final CommunicationOptions communicationOptions) { // init netty bootstrap Bootstrap bootstrap = new Bootstrap(); if (communicationOptions.getIoEventType() == BrpcConstants.IO_EVENT_NETTY_EPOLL) { bootstrap.channel(EpollSocketChannel.class); bootstrap.option(EpollChannelOption.EPOLL_MODE, EpollMode.EDGE_TRIGGERED); } else { bootstrap.channel(NioSocketChannel.class); } bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, communicationOptions.getConnectTimeoutMillis()); bootstrap.option(ChannelOption.SO_KEEPALIVE, communicationOptions.isKeepAlive()); bootstrap.option(ChannelOption.SO_REUSEADDR, communicationOptions.isReuseAddr()); bootstrap.option(ChannelOption.TCP_NODELAY, communicationOptions.isTcpNoDelay()); bootstrap.option(ChannelOption.SO_RCVBUF, communicationOptions.getReceiveBufferSize()); bootstrap.option(ChannelOption.SO_SNDBUF, communicationOptions.getSendBufferSize()); BrpcThreadPoolManager threadPoolManager = BrpcThreadPoolManager.getInstance(); boolean isSharing = communicationOptions.isGlobalThreadPoolSharing(); ThreadPool workThreadPool = threadPoolManager.getOrCreateClientWorkThreadPool( serviceName, isSharing, communicationOptions.getWorkThreadNum()); ExecutorService exceptionThreadPool = threadPoolManager.getExceptionThreadPool(); final RpcClientHandler rpcClientHandler = new RpcClientHandler(workThreadPool, exceptionThreadPool); final ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { if (communicationOptions.getChannelType() == ChannelType.SINGLE_CONNECTION) { ch.pipeline().addLast(new IdleStateHandler( 0, 0, communicationOptions.getKeepAliveTime())); ch.pipeline().addLast(new IdleChannelHandler()); } ch.pipeline().addLast(rpcClientHandler); } }; EventLoopGroup ioThreadPool = threadPoolManager.getOrCreateClientIoThreadPool( serviceName, isSharing, communicationOptions.getIoThreadNum(), communicationOptions.getIoEventType()); bootstrap.group(ioThreadPool).handler(initializer); return bootstrap; }
Example 12
Source File: ProxyHandlerTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override protected void test() throws Exception { final SuccessTestHandler testHandler = new SuccessTestHandler(); Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioSocketChannel.class); b.option(ChannelOption.AUTO_READ, ThreadLocalRandom.current().nextBoolean()); b.resolver(NoopAddressResolverGroup.INSTANCE); b.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(clientHandlers); p.addLast(new LineBasedFrameDecoder(64)); p.addLast(testHandler); } }); boolean finished = b.connect(destination).channel().closeFuture().await(10, TimeUnit.SECONDS); logger.debug("Received messages: {}", testHandler.received); if (testHandler.exceptions.isEmpty()) { logger.debug("No recorded exceptions on the client side."); } else { for (Throwable t : testHandler.exceptions) { logger.debug("Recorded exception on the client side: {}", t); } } assertProxyHandlers(true); assertThat(testHandler.received.toArray(), is(new Object[] { "0", "1", "2", "3" })); assertThat(testHandler.exceptions.toArray(), is(EmptyArrays.EMPTY_OBJECTS)); assertThat(testHandler.eventCount, is(expectedEventCount)); assertThat(finished, is(true)); }
Example 13
Source File: AbstractSocketTest.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Override protected void configure(ServerBootstrap bootstrap, Bootstrap bootstrap2, ByteBufAllocator allocator) { addr = newSocketAddress(); bootstrap.localAddress(addr); bootstrap.option(ChannelOption.ALLOCATOR, allocator); bootstrap.childOption(ChannelOption.ALLOCATOR, allocator); bootstrap2.remoteAddress(addr); bootstrap2.option(ChannelOption.ALLOCATOR, allocator); }
Example 14
Source File: UdpClient.java From easymodbus4j with GNU Lesser General Public License v3.0 | 5 votes |
public void setup(UdpClientHandler handler, boolean wait) throws InterruptedException { if (!isInit) { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.option(ChannelOption.SO_BROADCAST, true); b.group(group).channel(NioDatagramChannel.class).handler(handler); channel = b.bind(0).sync().channel(); sender = UdpSenderFactory.getInstance().get(channel); isInit = true; if (wait) { channel.closeFuture().await(); } } }
Example 15
Source File: NettyTcpTransport.java From qpid-jms with Apache License 2.0 | 5 votes |
private void configureNetty(Bootstrap bootstrap, TransportOptions options) { bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay()); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout()); bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive()); bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger()); if (options.getSendBufferSize() != -1) { bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize()); } if (options.getReceiveBufferSize() != -1) { bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize()); bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(options.getReceiveBufferSize())); } if (options.getTrafficClass() != -1) { bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass()); } if (options.getLocalAddress() != null || options.getLocalPort() != 0) { if(options.getLocalAddress() != null) { bootstrap.localAddress(options.getLocalAddress(), options.getLocalPort()); } else { bootstrap.localAddress(options.getLocalPort()); } } if (options.getProxyHandlerSupplier() != null) { // in case we have a proxy we do not want to resolve the address by ourselves but leave this to the proxy bootstrap.resolver(NoopAddressResolverGroup.INSTANCE); } }
Example 16
Source File: EpollReuseAddrTest.java From netty-4.1.22 with Apache License 2.0 | 4 votes |
@Test(timeout = 10000) @Ignore // TODO: Unignore after making it pass on centos6-1 and debian7-1 public void testMultipleBindDatagramChannel() throws Exception { ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED); Assume.assumeTrue(versionEqOrGt(3, 9, 0)); Bootstrap bootstrap = createBootstrap(); bootstrap.option(EpollChannelOption.SO_REUSEPORT, true); final AtomicBoolean received1 = new AtomicBoolean(); bootstrap.handler(new DatagramSocketTestHandler(received1)); ChannelFuture future = bootstrap.bind().syncUninterruptibly(); final InetSocketAddress address1 = (InetSocketAddress) future.channel().localAddress(); final AtomicBoolean received2 = new AtomicBoolean(); bootstrap.handler(new DatagramSocketTestHandler(received2)); ChannelFuture future2 = bootstrap.bind(address1).syncUninterruptibly(); final InetSocketAddress address2 = (InetSocketAddress) future2.channel().localAddress(); Assert.assertEquals(address1, address2); final byte[] bytes = "data".getBytes(); // fire up 16 Threads and send DatagramPackets to make sure we stress it enough to see DatagramPackets received // on both sockets. int count = 16; final CountDownLatch latch = new CountDownLatch(count); Runnable r = new Runnable() { @Override public void run() { try { DatagramSocket socket = new DatagramSocket(); while (!received1.get() || !received2.get()) { socket.send(new DatagramPacket( bytes, 0, bytes.length, address1.getAddress(), address1.getPort())); } socket.close(); } catch (IOException e) { e.printStackTrace(); } latch.countDown(); } }; ExecutorService executor = Executors.newFixedThreadPool(count); for (int i = 0 ; i < count; i++) { executor.execute(r); } latch.await(); executor.shutdown(); future.channel().close().syncUninterruptibly(); future2.channel().close().syncUninterruptibly(); Assert.assertTrue(received1.get()); Assert.assertTrue(received2.get()); }
Example 17
Source File: DatagramUnicastTest.java From netty-4.1.22 with Apache License 2.0 | 4 votes |
@SuppressWarnings("deprecation") private void testSimpleSend0(Bootstrap sb, Bootstrap cb, ByteBuf buf, boolean bindClient, final byte[] bytes, int count, WrapType wrapType) throws Throwable { Channel sc = null; Channel cc = null; try { cb.handler(new SimpleChannelInboundHandler<Object>() { @Override public void channelRead0(ChannelHandlerContext ctx, Object msgs) throws Exception { // Nothing will be sent. } }); final CountDownLatch latch = new CountDownLatch(count); sc = setupServerChannel(sb, bytes, latch); if (bindClient) { cc = cb.bind(newSocketAddress()).sync().channel(); } else { cb.option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true); cc = cb.register().sync().channel(); } InetSocketAddress addr = (InetSocketAddress) sc.localAddress(); for (int i = 0; i < count; i++) { switch (wrapType) { case DUP: cc.write(new DatagramPacket(buf.retainedDuplicate(), addr)); break; case SLICE: cc.write(new DatagramPacket(buf.retainedSlice(), addr)); break; case READ_ONLY: cc.write(new DatagramPacket(buf.retain().asReadOnly(), addr)); break; case NONE: cc.write(new DatagramPacket(buf.retain(), addr)); break; default: throw new Error("unknown wrap type: " + wrapType); } } // release as we used buf.retain() before cc.flush(); assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { // release as we used buf.retain() before buf.release(); closeChannel(cc); closeChannel(sc); } }
Example 18
Source File: SocketSpdyEchoTest.java From netty-4.1.22 with Apache License 2.0 | 4 votes |
private static void testSpdyEcho( ServerBootstrap sb, Bootstrap cb, final SpdyVersion version, boolean autoRead) throws Throwable { ByteBuf frames; switch (version) { case SPDY_3_1: frames = createFrames(3); break; default: throw new IllegalArgumentException("unknown version"); } sb.childOption(ChannelOption.AUTO_READ, autoRead); cb.option(ChannelOption.AUTO_READ, autoRead); final SpdyEchoTestServerHandler sh = new SpdyEchoTestServerHandler(autoRead); final SpdyEchoTestClientHandler ch = new SpdyEchoTestClientHandler(frames.copy(), autoRead); sb.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast( new SpdyFrameCodec(version), sh); } }); cb.handler(ch); Channel sc = sb.bind().sync().channel(); int port = ((InetSocketAddress) sc.localAddress()).getPort(); Channel cc = cb.connect(sc.localAddress()).sync().channel(); cc.writeAndFlush(frames); while (ch.counter < frames.writerIndex() - ignoredBytes) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(50); } catch (InterruptedException e) { // Ignore. } } if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) { throw ch.exception.get(); } if (sh.exception.get() != null) { throw sh.exception.get(); } if (ch.exception.get() != null) { throw ch.exception.get(); } }
Example 19
Source File: Cluster.java From tinkerpop with Apache License 2.0 | 4 votes |
Bootstrap createBootstrap() { final Bootstrap b = new Bootstrap().group(group); b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); return b; }
Example 20
Source File: Http2ClientLiveTest.java From tutorials with MIT License | 4 votes |
@Test public void whenRequestSent_thenHelloWorldReceived() throws Exception { EventLoopGroup workerGroup = new NioEventLoopGroup(); Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE, HOST, PORT); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(initializer); channel = b.connect() .syncUninterruptibly() .channel(); logger.info("Connected to [" + HOST + ':' + PORT + ']'); Http2SettingsHandler http2SettingsHandler = initializer.getSettingsHandler(); http2SettingsHandler.awaitSettings(60, TimeUnit.SECONDS); logger.info("Sending request(s)..."); FullHttpRequest request = Http2Util.createGetRequest(HOST, PORT); Http2ClientResponseHandler responseHandler = initializer.getResponseHandler(); int streamId = 3; responseHandler.put(streamId, channel.write(request), channel.newPromise()); channel.flush(); String response = responseHandler.awaitResponses(60, TimeUnit.SECONDS); assertEquals("Hello World", response); logger.info("Finished HTTP/2 request(s)"); } finally { workerGroup.shutdownGracefully(); } }