List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer
ChannelInitializer
From source file:com.phei.netty.protocol.http.xml.client.HttpXmlClient.java
License:Apache License
public void connect(int port) throws Exception { // ?NIO// www. ja v a2s.com EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { //????http? ch.pipeline().addLast("http-decoder", new HttpResponseDecoder()); //1Http????HTTP? ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); // XML? //http+XML?? ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true)); ch.pipeline().addLast("http-encoder", new HttpRequestEncoder()); ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder()); ch.pipeline().addLast("xmlClientHandler", new HttpXmlClientHandle()); } }); // ?? ChannelFuture f = b.connect(new InetSocketAddress(port)).sync(); // f.channel().closeFuture().sync(); } finally { // NIO group.shutdownGracefully(); } }
From source file:com.phei.netty.protocol.netty.server.NettyServer.java
License:Apache License
public void bind() throws Exception { // ??NIO/*from w ww . j a v a 2s . c o m*/ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100) //abstractBootstraphandlerNioServerSocketChannel .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws IOException { //?ServerBootstraphandlersocketchannel ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4)); ch.pipeline().addLast(new NettyMessageEncoder()); ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50)); ch.pipeline().addLast(new LoginAuthRespHandler()); ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler()); } }); // ??? b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync(); System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT)); }
From source file:com.phei.netty.protocol.websocket.server.WebSocketServer.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/* w w w. j a va 2 s .com*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //???http? pipeline.addLast("http-codec", new HttpServerCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); //???html5????websocket ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); pipeline.addLast("handler", new WebSocketServerHandler()); } }); Channel ch = b.bind(port).sync().channel(); System.out.println("Web socket server started at port " + port + '.'); System.out.println("Open your browser and navigate to http://localhost:" + port + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.qc.you.socket.server.Application.java
License:Apache License
@SuppressWarnings("unchecked") @Bean(name = "serverBootstrap") public ServerBootstrap bootstrap() { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup(), workerGroup()).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from w ww. ja v a 2s. c om*/ public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // Add the text line codec combination first, pipeline.addLast(new DelimiterBasedFrameDecoder(1024 * 1024, Delimiters.lineDelimiter())); // the encoder and decoder are static as these are sharable pipeline.addLast(DECODER); pipeline.addLast(ENCODER); pipeline.addLast(somethingServerHandler); pipeline.addLast(broadCastChannelHandler); } }); Map<ChannelOption<?>, Object> tcpChannelOptions = tcpChannelOptions(); Set<ChannelOption<?>> keySet = tcpChannelOptions.keySet(); for (@SuppressWarnings("rawtypes") ChannelOption option : keySet) { b.option(option, tcpChannelOptions.get(option)); } return b; }
From source file:com.quavo.osrs.network.NetworkExecutor.java
License:Open Source License
/** * Starts the network for a {@link Server}. * /*from w w w.ja va 2 s. c o m*/ * @param server The {@link Server} to use for building the network. * @return <True> If the network started successfully. */ public static void start() { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("decoder", new ConnectionDecoder()); pipeline.addLast("encoder", new ConnectionEncoder()); pipeline.addLast("adapter", new NetworkMessageHandler()); } }); bootstrap.childOption(ChannelOption.TCP_NODELAY, true); try { bootstrap.bind(Constants.HOST_NAME, Constants.HOST_PORT).sync(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Server successfully bootstrapped on port " + Constants.HOST_PORT + " and address " + Constants.HOST_NAME + "."); }
From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpMetricsIngestionServer.java
License:Apache License
/** * Starts the Ingest server//from w w w .ja va 2s . c o m * * @throws InterruptedException */ public void startServer() throws InterruptedException { RouteMatcher router = new RouteMatcher(); router.get("/v1.0", new DefaultHandler()); router.post("/v1.0/multitenant/experimental/metrics", new HttpMultitenantMetricsIngestionHandler(processor, timeout)); router.post("/v1.0/:tenantId/experimental/metrics", new HttpMetricsIngestionHandler(processor, timeout)); router.post("/v1.0/:tenantId/experimental/metrics/statsd", new HttpAggregatedIngestionHandler(processor, timeout)); router.get("/v2.0", new DefaultHandler()); router.post("/v2.0/:tenantId/ingest/multi", new HttpMultitenantMetricsIngestionHandler(processor, timeout)); router.post("/v2.0/:tenantId/ingest", new HttpMetricsIngestionHandler(processor, timeout)); router.post("/v2.0/:tenantId/ingest/aggregated", new HttpAggregatedIngestionHandler(processor, timeout)); router.post("/v2.0/:tenantId/events", getHttpEventsIngestionHandler()); router.post("/v2.0/:tenantId/ingest/aggregated/multi", new HttpAggregatedMultiIngestionHandler(processor, timeout)); final RouteMatcher finalRouter = router; log.info("Starting metrics listener HTTP server on port {}", httpIngestPort); ServerBootstrap server = new ServerBootstrap(); server.group(acceptorGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { setupPipeline(channel, finalRouter); } }); Channel channel = server.bind(new InetSocketAddress(httpIngestHost, httpIngestPort)).sync().channel(); allOpenChannels.add(channel); //register the tracker MBean for JMX/jolokia log.info("Registering tracker service"); Tracker.getInstance().register(); }
From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpMetricDataQueryServer.java
License:Apache License
public void startServer() throws InterruptedException { RouteMatcher router = new RouteMatcher(); router.get("/v1.0", new DefaultHandler()); router.get("/v1.0/:tenantId/experimental/views/metric_data/:metricName", new HttpRollupsQueryHandler()); router.post("/v1.0/:tenantId/experimental/views/metric_data", new HttpMultiRollupsQueryHandler()); router.post("/v2.0/:tenantId/views", new HttpMultiRollupsQueryHandler()); router.get("/v2.0", new DefaultHandler()); router.get("/v2.0/:tenantId/views/:metricName", new HttpRollupsQueryHandler()); router.get("/v2.0/:tenantId/metrics/search", new HttpMetricsIndexHandler()); router.get("/v2.0/:tenantId/metric_name/search", new HttpMetricTokensHandler()); router.get("/v2.0/:tenantId/events/getEvents", new HttpEventsQueryHandler(getEventsIO())); router.options("/v2.0/:tenantId/views/:metricName", new HttpOptionsHandler()); router.options("/v2.0/:tenantId/views", new HttpOptionsHandler()); router.options("/v2.0/:tenantId/metrics/search", new HttpOptionsHandler()); router.options("/v2.0/:tenantId/metric_name/search", new HttpOptionsHandler()); router.options("/v2.0/:tenantId/events/getEvents", new HttpOptionsHandler()); final RouteMatcher finalRouter = router; log.info("Starting metric data query server (HTTP) on port {}", this.httpQueryPort); ServerBootstrap server = new ServerBootstrap(); server.group(acceptorGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override//from w ww . j av a 2 s . c o m public void initChannel(SocketChannel channel) throws Exception { setupPipeline(channel, finalRouter); } }); serverChannel = server.bind(new InetSocketAddress(httpQueryHost, httpQueryPort)).sync().channel(); //register the tracker MBean for JMX/jolokia log.info("Registering tracker service"); Tracker.getInstance().register(); }
From source file:com.rain.websocketclient.WebSocketClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;//ww w.j a v a2 s . c o m } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { System.err.println("Only WS(S) is supported."); return; } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else { sslCtx = null; } EventLoopGroup group = new NioEventLoopGroup(); try { // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler); } }); Channel ch = b.connect(uri.getHost(), port).sync().channel(); handler.handshakeFuture().sync(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); while (true) { String msg = console.readLine(); if (msg == null) { break; } else if ("bye".equals(msg.toLowerCase())) { ch.writeAndFlush(new CloseWebSocketFrame()); ch.closeFuture().sync(); break; } else if ("ping".equals(msg.toLowerCase())) { WebSocketFrame frame = new PingWebSocketFrame( Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 })); ch.writeAndFlush(frame); } else { WebSocketFrame frame = new TextWebSocketFrame(msg); ch.writeAndFlush(frame); } } } finally { group.shutdownGracefully(); } }
From source file:com.relayrides.pushy.apns.ApnsClient.java
License:Open Source License
protected ApnsClient(final SslContext sslContext, final EventLoopGroup eventLoopGroup) { this.bootstrap = new Bootstrap(); if (eventLoopGroup != null) { this.bootstrap.group(eventLoopGroup); this.shouldShutDownEventLoopGroup = false; } else {// ww w. j a v a 2s.c o m this.bootstrap.group(new NioEventLoopGroup(1)); this.shouldShutDownEventLoopGroup = true; } this.bootstrap.channel(SocketChannelClassUtil.getSocketChannelClass(this.bootstrap.config().group())); this.bootstrap.option(ChannelOption.TCP_NODELAY, true); this.bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); final ProxyHandlerFactory proxyHandlerFactory = ApnsClient.this.proxyHandlerFactory; if (proxyHandlerFactory != null) { pipeline.addFirst(proxyHandlerFactory.createProxyHandler()); } if (ApnsClient.this.writeTimeoutMillis > 0) { pipeline.addLast( new WriteTimeoutHandler(ApnsClient.this.writeTimeoutMillis, TimeUnit.MILLISECONDS)); } pipeline.addLast(sslContext.newHandler(channel.alloc())); pipeline.addLast(new ApplicationProtocolNegotiationHandler("") { @Override protected void configurePipeline(final ChannelHandlerContext context, final String protocol) { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { final ApnsClientHandler apnsClientHandler = new ApnsClientHandler.ApnsClientHandlerBuilder() .server(false).apnsClient(ApnsClient.this) .authority( ((InetSocketAddress) context.channel().remoteAddress()).getHostName()) .encoderEnforceMaxConcurrentStreams(true).build(); synchronized (ApnsClient.this.bootstrap) { if (ApnsClient.this.gracefulShutdownTimeoutMillis != null) { apnsClientHandler.gracefulShutdownTimeoutMillis( ApnsClient.this.gracefulShutdownTimeoutMillis); } } context.pipeline().addLast( new IdleStateHandler(0, 0, PING_IDLE_TIME_MILLIS, TimeUnit.MILLISECONDS)); context.pipeline().addLast(apnsClientHandler); final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise; if (connectionReadyPromise != null) { connectionReadyPromise.trySuccess(); } } else { throw new IllegalArgumentException("Unexpected protocol: " + protocol); } } }); } }); }
From source file:com.relayrides.pushy.apns.ApnsClientThread.java
License:Open Source License
/** * Constructs a new APNs client thread. The thread connects to the APNs gateway in the given {@code PushManager}'s * environment and reads notifications from the {@code PushManager}'s queue. * // w w w. j a v a2 s .c o m * @param pushManager the {@code PushManager} from which this client thread should read environment settings and * notifications */ public ApnsClientThread(final PushManager<T> pushManager) { super(String.format("ApnsClientThread-%d", ApnsClientThread.threadCounter.incrementAndGet())); this.pushManager = pushManager; this.sentNotificationBuffer = new SentNotificationBuffer<T>(SENT_NOTIFICATION_BUFFER_SIZE); this.bootstrap = new Bootstrap(); this.bootstrap.group(this.pushManager.getWorkerGroup()); this.bootstrap.channel(NioSocketChannel.class); this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true); final ApnsClientThread<T> clientThread = this; this.bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); if (pushManager.getEnvironment().isTlsRequired()) { pipeline.addLast("ssl", SslHandlerUtil.createSslHandler(pushManager.getKeyStore(), pushManager.getKeyStorePassword())); } pipeline.addLast("decoder", new RejectedNotificationDecoder()); pipeline.addLast("encoder", new ApnsPushNotificationEncoder()); pipeline.addLast("handler", new ApnsErrorHandler(clientThread)); } }); }