io.netty.channel.nio.NioEventLoopGroup Java Examples
The following examples show how to use
io.netty.channel.nio.NioEventLoopGroup.
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: 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 #2
Source File: TestServer.java From jdk-source-analysis with Apache License 2.0 | 6 votes |
@Test public void test() throws InterruptedException { NioEventLoopGroup bossGroup = new NioEventLoopGroup(1); NioEventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new TestServerInitializer()); ChannelFuture future = bootstrap.bind(11911).sync(); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example #3
Source File: DiscoveryThread.java From JRakNet with MIT License | 6 votes |
/** * Allocates a discovery thread. */ protected DiscoveryThread() { this.logger = LogManager.getLogger(DiscoveryThread.class); this.bootstrap = new Bootstrap(); this.group = new NioEventLoopGroup(); this.handler = new DiscoveryHandler(); bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler); bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false); try { this.channel = bootstrap.bind(0).sync().channel(); } catch (InterruptedException e) { this.interrupt(); // Cause thread to immediately break out of loop Discovery.setDiscoveryMode(DiscoveryMode.DISABLED); logger.error("Failed to bind channel necessary for broadcasting pings, disabled discovery system"); } this.setName(logger.getName()); }
Example #4
Source File: ArchistarS3.java From archistar-core with GNU General Public License v2.0 | 6 votes |
private static Engine createEngine() { NioEventLoopGroup loopGroup = new NioEventLoopGroup(16); TestServerConfiguration serverConfig = new TestServerConfiguration(createNewServers(), loopGroup); serverConfig.setupTestServer(1); try { CryptoEngine crypto = new RabinBenOrEngine(4, 3, new FakeRandomSource()); Distributor distributor = new BFTDistributor(serverConfig, loopGroup); MetadataService metadata = new SimpleMetadataService(serverConfig, distributor, crypto); return new Engine(serverConfig, metadata, distributor, crypto); } catch (NoSuchAlgorithmException | WeakSecurityException ex) { assert(false); } return null; }
Example #5
Source File: FastdfsExecutor.java From fastdfs-client with Apache License 2.0 | 6 votes |
FastdfsExecutor(FastdfsSettings settings) { loopGroup = new NioEventLoopGroup(settings.maxThreads(), new ThreadFactory() { final String threadPrefix = "fastdfs-"; final AtomicInteger threadNumber = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { return new Thread(null, r, threadPrefix + threadNumber.getAndIncrement()); } }); poolGroup = new FastdfsPoolGroup( loopGroup, settings.connectTimeout(), settings.readTimeout(), settings.idleTimeout(), settings.maxConnPerHost(), settings.maxPendingRequests() ); }
Example #6
Source File: EchoTest.java From jdk-source-analysis with Apache License 2.0 | 6 votes |
@Test public void testServer() throws InterruptedException { EchoServerHandler serverHandler = new EchoServerHandler(); EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup wokerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, wokerGroup) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(PORT)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(serverHandler); } }); ChannelFuture f = b.bind().sync(); f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully().sync(); wokerGroup.shutdownGracefully().sync(); } }
Example #7
Source File: MqttTransportService.java From iotplatform with Apache License 2.0 | 6 votes |
@PostConstruct public void init() throws Exception { log.info("Setting resource leak detector level to {}", leakDetectorLevel); ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase())); log.info("Starting MQTT transport..."); log.info("Lookup MQTT transport adaptor {}", adaptorName); // this.adaptor = (MqttTransportAdaptor) appContext.getBean(adaptorName); log.info("Starting MQTT transport server"); bossGroup = new NioEventLoopGroup(bossGroupThreadCount); workerGroup = new NioEventLoopGroup(workerGroupThreadCount); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 1000).option(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class) .childHandler(new MqttTransportServerInitializer(msgProducer, deviceService, authService, assetService, assetAuthService, relationService, sslHandlerProvider)); serverChannel = b.bind(host, port).sync().channel(); log.info("Mqtt transport started: {}:{}!", host, port); }
Example #8
Source File: NettyTransportClient.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 6 votes |
private Bootstrap initClientBootstrap() { Bootstrap b = new Bootstrap(); eventLoopGroup = new NioEventLoopGroup(); b.group(eventLoopGroup) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ClusterClientConfigManager.getConnectTimeout()) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { clientHandler = new TokenClientHandler(currentState, disconnectCallback); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2)); pipeline.addLast(new NettyResponseDecoder()); pipeline.addLast(new LengthFieldPrepender(2)); pipeline.addLast(new NettyRequestEncoder()); pipeline.addLast(clientHandler); } }); return b; }
Example #9
Source File: SecureChatServer.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate(); SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new SecureChatServerInitializer(sslCtx)); b.bind(PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example #10
Source File: SynapseClient.java From SynapseAPI with GNU General Public License v3.0 | 6 votes |
public boolean connect() { clientGroup = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); //服务引导程序,服务器端快速启动程序 b.group(clientGroup) .channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new SynapseClientInitializer(this)); b.connect(this.interfaz, this.port).get(); // 等待服务端监听端口关闭,等待服务端链路关闭之后main函数才退出 //future.channel().closeFuture().sync(); return true; } catch (Exception e) { clientGroup.shutdownGracefully(); Server.getInstance().getLogger().alert("Synapse Client can't connect to server: " + this.interfaz + ":" + this.port); Server.getInstance().getLogger().alert("Reason: " + e.getLocalizedMessage()); Server.getInstance().getLogger().warning("We will reconnect in 3 seconds"); this.reconnect(); return false; } }
Example #11
Source File: URLHttpDownBootstrapBuilder.java From pdown-core with MIT License | 6 votes |
@Override public HttpDownBootstrap build() { try { HttpRequestInfo request = HttpDownUtil.buildRequest(method, url, heads, body); request(request); if (getLoopGroup() == null) { loopGroup(new NioEventLoopGroup(1)); } HttpResponseInfo response = HttpDownUtil.getHttpResponseInfo(request, null, getProxyConfig(), getLoopGroup()); if (getResponse() == null) { response(response); } else { if (StringUtil.isNullOrEmpty(getResponse().getFileName())) { getResponse().setFileName(response.getFileName()); } getResponse().setSupportRange(response.isSupportRange()); getResponse().setTotalSize(response.getTotalSize()); } } catch (Exception e) { if (getLoopGroup() != null) { getLoopGroup().shutdownGracefully(); } throw new BootstrapBuildException("build URLHttpDownBootstrap error", e); } return super.build(); }
Example #12
Source File: VoodooSparkProtocolHandler.java From diozero with MIT License | 6 votes |
private void connect(String host, int port) throws InterruptedException { workerGroup = new NioEventLoopGroup(); ResponseHandler rh = new ResponseHandler(this::messageReceived); Bootstrap b1 = new Bootstrap(); b1.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ResponseDecoder(), new MessageEncoder(), rh); } }); // Connect messageChannel = b1.connect(host, port).sync().channel(); }
Example #13
Source File: ExtractorServer.java From deep-spark with Apache License 2.0 | 6 votes |
public static void start() throws CertificateException, SSLException, InterruptedException { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ExtractorServerInitializer(sslCtx)); b.bind(PORT).sync().channel().closeFuture().sync(); }
Example #14
Source File: AsyncNettyClientTest.java From x-pipe with Apache License 2.0 | 6 votes |
protected void doStart() throws Exception { EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1, XpipeThreadFactory.create("NettyKeyedPoolClientFactory")); b.group(eventLoopGroup).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(new LoggingHandler()); p.addLast(new NettySimpleMessageHandler()); p.addLast(new NettyClientHandler()); } }); }
Example #15
Source File: BasicSSLServer.java From elasticsearch-hadoop with Apache License 2.0 | 6 votes |
public void start() throws Exception { File cert = Paths.get(getClass().getResource("/ssl/server.pem").toURI()).toFile(); File keyStore = Paths.get(getClass().getResource("/ssl/server.key").toURI()).toFile(); SslContext sslCtx = SslContext.newServerContext(cert, keyStore); bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); server = new ServerBootstrap(); server.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new BasicSSLServerInitializer(sslCtx)); server.bind(port).sync().channel().closeFuture(); }
Example #16
Source File: Server.java From blog with BSD 2-Clause "Simplified" License | 6 votes |
public static void start(final int port) throws Exception { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup woker = new NioEventLoopGroup(); ServerBootstrap serverBootstrap = new ServerBootstrap(); try { serverBootstrap.channel(NioServerSocketChannel.class).group(boss, woker) .childOption(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-decoder", new HttpServerCodec()); ch.pipeline().addLast(new HttpServerHandler()); } }); ChannelFuture future = serverBootstrap.bind(port).sync(); System.out.println("server start ok port is " + port); DataCenter.start(); future.channel().closeFuture().sync(); } finally { boss.shutdownGracefully(); woker.shutdownGracefully(); } }
Example #17
Source File: EchoClient.java From Lottor with MIT License | 6 votes |
public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) // 注册线程池 .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类 .remoteAddress(new InetSocketAddress(this.host, this.port)) // 绑定连接端口和host信息 .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器 @Override protected void initChannel(SocketChannel ch) throws Exception { System.out.println("connected..."); ch.pipeline().addLast(new EchoClientHandler()); } }); System.out.println("created.."); ChannelFuture cf = b.connect().sync(); // 异步连接服务器 System.out.println("connected..."); // 连接完成 cf.channel().closeFuture().sync(); // 异步等待关闭连接channel System.out.println("closed.."); // 关闭完成 } finally { group.shutdownGracefully().sync(); // 释放线程池资源 } }
Example #18
Source File: Netty4DataSourceSupplier.java From ndbc with Apache License 2.0 | 5 votes |
public Netty4DataSourceSupplier(final Config config, final Function<BufferReader, Optional<BufferReader>> transformBufferReader) { this.config = config; final ChannelSupplier channelSupplier = new ChannelSupplier( new NioEventLoopGroup(config.nioThreads().orElse(0), new DefaultThreadFactory("ndbc-netty4", true)), config.host(), config.port(), config.charset(), transformBufferReader); this.createConnection = createConnectionSupplier(config, channelSupplier); }
Example #19
Source File: BaseServerTemplate.java From learning-code with Apache License 2.0 | 5 votes |
public void serverTask(ChannelHandler... channelHandlers) { // bossGroup 用来接收进来的连接 EventLoopGroup bossGroup = new NioEventLoopGroup(); // boss 接收的连接注册在 worker 上 EventLoopGroup workerGroup = new NioEventLoopGroup(); // nio 服务启动辅助类 ServerBootstrap bootstrap = new ServerBootstrap(); try { bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) // 处理一个已经接收的 channel, 自定义事件处理 .childHandler(handler()) // 提供 NioServerSocketChannel 用来接收连接的属性设置 .option(ChannelOption.SO_BACKLOG, 128) // 提供父管道 ServerChannel 接收到连接的属性设置 .childOption(ChannelOption.SO_KEEPALIVE, true); // 绑定端口,启动,接收进来的连接 ChannelFuture channelFuture = bootstrap.bind(port).sync(); // 服务器 socket 关闭 channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { // 优雅退出 workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
Example #20
Source File: ProxyThreadPools.java From g4proxy with Apache License 2.0 | 5 votes |
public ProxyThreadPools(SelectorProvider selectorProvider, int incomingAcceptorThreads, int incomingWorkerThreads, int outgoingWorkerThreads, String serverGroupName, int serverGroupId) { clientToProxyAcceptorPool = new NioEventLoopGroup(incomingAcceptorThreads, new CategorizedThreadFactory(serverGroupName, "ClientToProxyAcceptor", serverGroupId), selectorProvider); clientToProxyWorkerPool = new NioEventLoopGroup(incomingWorkerThreads, new CategorizedThreadFactory(serverGroupName, "ClientToProxyWorker", serverGroupId), selectorProvider); clientToProxyWorkerPool.setIoRatio(90); proxyToServerWorkerPool = new NioEventLoopGroup(outgoingWorkerThreads, new CategorizedThreadFactory(serverGroupName, "ProxyToServerWorker", serverGroupId), selectorProvider); proxyToServerWorkerPool.setIoRatio(90); }
Example #21
Source File: DynoRedissonClient.java From dyno with Apache License 2.0 | 5 votes |
public DynoRedissonClient build() { assert (appName != null); assert (clusterName != null); assert (cpConfig != null); DynoCPMonitor cpMonitor = new DynoCPMonitor(appName); DynoOPMonitor opMonitor = new DynoOPMonitor(appName); RedissonConnectionFactory connFactory = new RedissonConnectionFactory(new NioEventLoopGroup(4), opMonitor); ConnectionPoolImpl<RedisAsyncConnection<String, String>> pool = new ConnectionPoolImpl<RedisAsyncConnection<String, String>>( connFactory, cpConfig, cpMonitor, Type.Async); try { pool.start().get(); } catch (Exception e) { if (cpConfig.getFailOnStartupIfNoHosts()) { throw new RuntimeException(e); } Logger.warn("UNABLE TO START CONNECTION POOL -- IDLING"); pool.idle(); } final DynoRedissonClient client = new DynoRedissonClient(appName, pool); return client; }
Example #22
Source File: NettyServer.java From ClusterDeviceControlPlatform with MIT License | 5 votes |
@Override public void start() { new Thread(() -> { group = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(group) .channel(NioServerSocketChannel.class) .childHandler(serverChannelInitializer); ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(30232)); channelFuture.addListener(future -> startListenerHandle(future, launchListener)); }).start(); }
Example #23
Source File: Server.java From neoscada with Eclipse Public License 1.0 | 5 votes |
public Server ( final SocketAddress address, final ProtocolOptions options, final List<ServerModule> modules ) { this.options = options; this.manager = new MessageManager ( this.options ); this.bossGroup = new NioEventLoopGroup (); this.workerGroup = new NioEventLoopGroup (); this.bootstrap = new ServerBootstrap (); this.bootstrap.group ( this.bossGroup, this.workerGroup ); this.bootstrap.channel ( NioServerSocketChannel.class ); this.bootstrap.option ( ChannelOption.SO_BACKLOG, 5 ); this.bootstrap.option ( ChannelOption.SO_REUSEADDR, true ); this.bootstrap.childHandler ( new ChannelInitializer<SocketChannel> () { @Override protected void initChannel ( final SocketChannel ch ) throws Exception { handleInitChannel ( ch ); } } ); this.modules = modules.toArray ( new ServerModule[modules.size ()] ); for ( final ServerModule module : modules ) { module.initializeServer ( this, this.manager ); } this.channel = this.bootstrap.bind ( address ).channel (); }
Example #24
Source File: HttpSnoopServer.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HttpSnoopServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.err.println("Open your web browser and navigate to " + (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example #25
Source File: HandshakerServiceChannel.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
/** Returns a fixed object pool of handshaker service channel for testing only. */ static FixedObjectPool<ManagedChannel> getHandshakerChannelPoolForTesting( String handshakerAddress) { ThreadFactory clientThreadFactory = new DefaultThreadFactory("handshaker pool", true); ManagedChannel channel = NettyChannelBuilder.forTarget(handshakerAddress) .directExecutor() .eventLoopGroup(new NioEventLoopGroup(1, clientThreadFactory)) .usePlaintext() .build(); return new FixedObjectPool<ManagedChannel>(channel); }
Example #26
Source File: Http2Server.java From glowroot with Apache License 2.0 | 5 votes |
Http2Server(int port, boolean supportHttp1) throws InterruptedException { group = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(group) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(supportHttp1 ? new Http2ServerWithHttp1SupportInitializer() : new Http2ServerInitializer()); channel = b.bind(port).sync().channel(); }
Example #27
Source File: NettyTcpClient.java From NettyChat with Apache License 2.0 | 5 votes |
/** * 初始化bootstrap */ private void initBootstrap() { EventLoopGroup loopGroup = new NioEventLoopGroup(4); bootstrap = new Bootstrap(); bootstrap.group(loopGroup).channel(NioSocketChannel.class); // 设置该选项以后,如果在两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文 bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // 设置禁用nagle算法 bootstrap.option(ChannelOption.TCP_NODELAY, true); // 设置连接超时时长 bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeout()); // 设置初始化Channel bootstrap.handler(new TCPChannelInitializerHandler(this)); }
Example #28
Source File: HttpFileServer.java From tajo with Apache License 2.0 | 5 votes |
public HttpFileServer(final InetSocketAddress addr) { this.addr = addr; this.eventloopGroup = new NioEventLoopGroup(2, Executors.defaultThreadFactory()); // Configure the server. this.bootstrap = new ServerBootstrap(); this.bootstrap.childHandler(new HttpFileServerChannelInitializer()) .group(eventloopGroup) .option(ChannelOption.TCP_NODELAY, true) .channel(NioServerSocketChannel.class); this.channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); }
Example #29
Source File: LineBasedServer.java From netty-learning with Apache License 2.0 | 5 votes |
public void bind(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new LineBasedFrameDecoder(1024)); p.addLast(new StringDecoder()); p.addLast(new StringEncoder()); p.addLast(new LineServerHandler()); } }); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(port).sync(); // (7) logger.info("server bind port:{}", port); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example #30
Source File: CIMNioSocketAcceptor.java From cim with Apache License 2.0 | 5 votes |
private void bindWebPort(){ webBossGroup = new NioEventLoopGroup(); webWorkerGroup = new NioEventLoopGroup(); ServerBootstrap bootstrap = createServerBootstrap(webBossGroup,webWorkerGroup); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch){ ch.pipeline().addLast(new HttpServerCodec()); ch.pipeline().addLast(new ChunkedWriteHandler()); ch.pipeline().addLast(new HttpObjectAggregator(65536)); ch.pipeline().addLast(new WebMessageEncoder()); ch.pipeline().addLast(new WebMessageDecoder()); ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO)); ch.pipeline().addLast(channelEventHandler); } }); ChannelFuture channelFuture = bootstrap.bind(webPort).syncUninterruptibly(); channelFuture.channel().newSucceededFuture().addListener(future -> { String logBanner = "\n\n" + "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" + "* *\n" + "* *\n" + "* Websocket Server started on port {}. *\n" + "* *\n" + "* *\n" + "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n"; LOGGER.info(logBanner, webPort); }); channelFuture.channel().closeFuture().addListener(future -> this.destroy(webBossGroup,webWorkerGroup)); }