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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: WebSocketServer.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; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new WebSocketServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.out.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 #19
Source File: ReaderServer.java From disthene-reader with MIT License | 5 votes |
public void run() throws InterruptedException { bossGroup = new NioEventLoopGroup(configuration.getThreads()); workerGroup = new NioEventLoopGroup(configuration.getThreads()); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpRequestDecoder( configuration.getMaxInitialLineLength(), configuration.getMaxHeaderSize(), configuration.getMaxChunkSize() )); p.addLast(new HttpObjectAggregator(MAX_CONTENT_LENGTH)); p.addLast(new HttpResponseEncoder()); p.addLast(new HttpContentCompressor()); p.addLast(new ReaderServerHandler(handlers)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error(cause); super.exceptionCaught(ctx, cause); } }); // Start the server. b.bind(configuration.getBind(), configuration.getPort()).sync(); }
Example #20
Source File: WebWhoisActionHandlerTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testAdvanced_redirect() { // Sets up EventLoopGroup with 1 thread to be blocking. EventLoopGroup group = new NioEventLoopGroup(1); // Sets up embedded channel. setup("", makeBootstrap(group), false); setupChannel(initialProtocol); // Initializes LocalAddress with unique String. LocalAddress address = new LocalAddress(TARGET_HOST); // stores future ChannelFuture future = actionHandler.getFinishedFuture(); channel.writeOutbound(msg); // Path that we test WebWhoisActionHandler uses. String path = "/test"; // Sets up the local server that the handler will be redirected to. TestServer.webWhoisServer(group, address, "", TARGET_HOST, path); FullHttpResponse response = new HttpResponseMessage( makeRedirectResponse( HttpResponseStatus.MOVED_PERMANENTLY, HTTP_REDIRECT + TARGET_HOST + path, true)); // checks that future has not been set to successful or a failure assertThat(future.isDone()).isFalse(); channel.writeInbound(response); // makes sure old channel is shut down when attempting redirection assertThat(channel.isActive()).isFalse(); // assesses that we successfully received good response and protocol is unchanged assertThat(future.syncUninterruptibly().isSuccess()).isTrue(); }
Example #21
Source File: Connector.java From multi-model-server with Apache License 2.0 | 5 votes |
public static EventLoopGroup newEventLoopGroup(int threads) { if (useNativeIo && Epoll.isAvailable()) { return new EpollEventLoopGroup(threads); } else if (useNativeIo && KQueue.isAvailable()) { return new KQueueEventLoopGroup(threads); } NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(threads); eventLoopGroup.setIoRatio(ConfigManager.getInstance().getIoRatio()); return eventLoopGroup; }
Example #22
Source File: CtpClient.java From ftdc with Apache License 2.0 | 5 votes |
/** * * @param host 180.168.146.187 * @param port 10030|10000 * @throws Exception */ public static void ctp(String host, int port, ChannelFutureListener listener) throws Exception { NioEventLoopGroup group = new NioEventLoopGroup(); Bootstrap bs = new Bootstrap(); bs.group(group); bs.channel(NioSocketChannel.class); bs.handler(new FtdcInitializer()); ChannelFuture channelFuture = bs.connect(host, port); channelFuture.addListener(listener); channelFuture.sync(); }
Example #23
Source File: NettyClient.java From rpcx-java with Apache License 2.0 | 5 votes |
public NettyClient(IServiceDiscovery serviceDiscovery) { this.semaphoreOneway = new Semaphore(1000, true); this.semaphoreAsync = new Semaphore(1000, true); this.serviceDiscovery = serviceDiscovery; this.eventLoopGroupWorker = new NioEventLoopGroup(1, new NamedThreadFactory("NettyClientSelector_")); this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(nettyClientConfig.getClientWorkerThreads(), new NamedThreadFactory("NettyClientWorkerThread_")); this.bootstrap = createBootstrap(); startScanResponseTableSchedule(); runEventListener(); }
Example #24
Source File: ConnectionPoolImpl.java From pravega with Apache License 2.0 | 5 votes |
private EventLoopGroup getEventLoopGroup() { if (Epoll.isAvailable()) { return new EpollEventLoopGroup(); } else { log.warn("Epoll not available. Falling back on NIO."); return new NioEventLoopGroup(); } }
Example #25
Source File: TimeClient.java From netty-learning with MIT License | 5 votes |
public static void main(String[] args) throws InterruptedException { String host = "127.0.0.1" ; int port = 11211 ; EventLoopGroup group = new NioEventLoopGroup() ; try { Bootstrap bootstrap = new Bootstrap() ; bootstrap.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE,true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new TimeClientHandler()) ; } }); // 启动客户端 ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); // 等待连接关闭 channelFuture.channel().closeFuture().sync() ; }finally { group.shutdownGracefully(); } }
Example #26
Source File: WebSocketIT.java From qonduit with Apache License 2.0 | 5 votes |
@Before public void setup() throws Exception { s = new Server(conf); s.run(); Connector con = mac.getConnector("root", "secret"); con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F")); this.sessionId = UUID.randomUUID().toString(); AuthCache.getCache().put(sessionId, token); group = new NioEventLoopGroup(); SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId); HttpHeaders headers = new DefaultHttpHeaders(); headers.add(HttpHeaderNames.COOKIE, cookieVal); WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION, WebSocketVersion.V13, (String) null, false, headers); handler = new ClientHandler(handshaker); Bootstrap boot = new Bootstrap(); boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT)); ch.pipeline().addLast(new HttpClientCodec()); ch.pipeline().addLast(new HttpObjectAggregator(8192)); ch.pipeline().addLast(handler); } }); ch = boot.connect("127.0.0.1", WS_PORT).sync().channel(); // Wait until handshake is complete while (!handshaker.isHandshakeComplete()) { sleepUninterruptibly(500, TimeUnit.MILLISECONDS); LOG.debug("Waiting for Handshake to complete"); } }
Example #27
Source File: WhirlpoolServer.java From whirlpool with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { // 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 ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8)); p.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8)); p.addLast("aggregator", new HttpObjectAggregator(65536)); p.addLast("handler", new WhirlpoolServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); logger.info("Whirlpool Server started"); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { logger.info("Whirlpool Server shutdown started"); // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); logger.info("Whirlpool Server shutdown completed"); } }
Example #28
Source File: TransportTypeHolder.java From blynk-server with GNU General Public License v3.0 | 5 votes |
private TransportTypeHolder(int workerThreads) { if (Epoll.isAvailable()) { log.info("Using native epoll transport."); bossGroup = new EpollEventLoopGroup(1); workerGroup = new EpollEventLoopGroup(workerThreads); channelClass = EpollServerSocketChannel.class; } else { bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(workerThreads); channelClass = NioServerSocketChannel.class; } }
Example #29
Source File: Client.java From neoscada with Eclipse Public License 1.0 | 5 votes |
public Client ( final SocketAddress address, final ConnectionStateListener listener, final ProtocolOptions options, final List<ClientModule> modules ) { this.address = address; this.options = options; this.listener = listener; this.manager = new MessageManager ( options ); this.group = new NioEventLoopGroup (); this.bootstrap = new Bootstrap (); this.bootstrap.group ( this.group ); this.bootstrap.channel ( NioSocketChannel.class ); this.bootstrap.handler ( new ChannelInitializer<SocketChannel> () { @Override protected void initChannel ( final SocketChannel ch ) throws Exception { handleInitChannel ( ch ); } } ); this.modules = modules.toArray ( new ClientModule[modules.size ()] ); this.executor = Executors.newSingleThreadExecutor ( new NamedThreadFactory ( "IEC60870Client/" + address ) ); for ( final ClientModule module : modules ) { module.initializeClient ( this, this.manager ); } }
Example #30
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(); } }