io.netty.handler.codec.http.HttpServerCodec Java Examples

The following examples show how to use io.netty.handler.codec.http.HttpServerCodec. 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: HttpServerInitializer.java    From ns4_frame with Apache License 2.0 6 votes vote down vote up
@Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline p = socketChannel.pipeline();
        ChannelConfig channelConfig = new ChannelConfig();
        //判断是否是https
        //是https获取对应的sslengine 添加sslhandler
        if (sslContext != null) 
		{
//        	DeterMineHttpsHandler deterMineHttpsHandler = new DeterMineHttpsHandler();
//	        p.addLast("determine",deterMineHttpsHandler);
//	        p.addLast("sslcontroller",new SslController(sslContext, deterMineHttpsHandler, socketChannel,channelConfig));
        	channelConfig.setPosibleHttps(true);
        	p.addLast("sslHandler",sslContext.newHandler(socketChannel.alloc()));
        	
		}
	        
        p.addLast("httpservercode",new HttpServerCodec(4096, 8192, 8192,false));
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpDispatcherServerHandler(channelConfig));
        p.addLast(new HttpRPCHandler());
    }
 
Example #2
Source File: WebSocketInitializer.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
public void addHandlers(final Channel ch) {
    ch.pipeline().addBefore(AbstractChannelInitializer.FIRST_ABSTRACT_HANDLER, HTTP_SERVER_CODEC, new HttpServerCodec());
    ch.pipeline().addAfter(HTTP_SERVER_CODEC, HTTP_OBJECT_AGGREGATOR, new HttpObjectAggregator(WEBSOCKET_MAX_CONTENT_LENGTH));

    final String webSocketPath = websocketListener.getPath();
    final String subprotocols = getSubprotocolString();
    final boolean allowExtensions = websocketListener.getAllowExtensions();

    ch.pipeline().addAfter(HTTP_OBJECT_AGGREGATOR, WEBSOCKET_SERVER_PROTOCOL_HANDLER, new WebSocketServerProtocolHandler(webSocketPath, subprotocols, allowExtensions, Integer.MAX_VALUE));
    ch.pipeline().addAfter(WEBSOCKET_SERVER_PROTOCOL_HANDLER, WEBSOCKET_BINARY_FRAME_HANDLER, new WebSocketBinaryFrameHandler());
    ch.pipeline().addAfter(WEBSOCKET_BINARY_FRAME_HANDLER, WEBSOCKET_CONTINUATION_FRAME_HANDLER, new WebSocketContinuationFrameHandler());
    ch.pipeline().addAfter(WEBSOCKET_BINARY_FRAME_HANDLER, WEBSOCKET_TEXT_FRAME_HANDLER, new WebSocketTextFrameHandler());

    ch.pipeline().addAfter(WEBSOCKET_TEXT_FRAME_HANDLER, MQTT_WEBSOCKET_ENCODER, new MQTTWebsocketEncoder());

}
 
Example #3
Source File: TtyServerInitializer.java    From termd with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipeline = ch.pipeline();
  pipeline.addLast(new HttpServerCodec());
  pipeline.addLast(new ChunkedWriteHandler());
  pipeline.addLast(new HttpObjectAggregator(64 * 1024));
  HttpRequestHandler httpRequestHandler = null;
      if (httpResourcePath == null) {
          httpRequestHandler = new HttpRequestHandler("/ws");
      } else {
          httpRequestHandler = new HttpRequestHandler("/ws", httpResourcePath);
      }

  pipeline.addLast(httpRequestHandler);
  pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
  pipeline.addLast(new TtyWebSocketFrameHandler(group, handler, HttpRequestHandler.class));
}
 
Example #4
Source File: HttpRequestInitializer.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
   PREVIEW_STARTED.inc();

   ChannelPipeline pipeline = ch.pipeline();
   pipeline.addLast(inboundIpTracking);

   if (serverTlsContext != null && serverTlsContext.useTls()) {
      SSLEngine engine = serverTlsContext.getContext().newEngine(ch.alloc());
      engine.setNeedClientAuth(serverConfig.isTlsNeedClientAuth());
      engine.setUseClientMode(false);
      pipeline.addLast(FILTER_SSL, new SslHandler(engine));
   }

   pipeline.addLast(FILTER_CODEC, new HttpServerCodec());
   pipeline.addLast(FILTER_HTTP_AGGREGATOR, new HttpObjectAggregator(65536));
   pipeline.addLast("ChunkedWriteHandler", new ChunkedWriteHandler());
   pipeline.addLast("bind-client-context", bindClient);
   pipeline.addLast(FILTER_HANDLER, handlerProvider.get());
   pipeline.addLast(outboundIpTracking);

   ch.pipeline().addAfter(FILTER_HTTP_AGGREGATOR, "corshandler", new CorsHandler(corsConfig.build()));
}
 
Example #5
Source File: HttpRequestInitializer.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   UPLOAD_STARTED.inc();

   pipeline.addLast(inboundIpTracking);
   if (serverTlsContext != null && serverTlsContext.useTls()) {
      SSLEngine engine = serverTlsContext.getContext().newEngine(ch.alloc());
      SslHandler handler = new SslHandler(engine);
      handler.setHandshakeTimeout(config.getSslHandshakeTimeout(), TimeUnit.MILLISECONDS);
      handler.setCloseNotifyTimeout(config.getSslCloseNotifyTimeout(), TimeUnit.MILLISECONDS);

      engine.setNeedClientAuth(serverConfig.isTlsNeedClientAuth());
      engine.setUseClientMode(false);
      pipeline.addLast(FILTER_SSL, handler);
   }

   pipeline.addLast(FILTER_CODEC, new HttpServerCodec());
   pipeline.addLast(FILTER_HTTP_AGGREGATOR, new HttpObjectAggregator(config.getMaxPreviewSize()));
   pipeline.addLast(FILTER_HANDLER, handlerProvider.get());
   pipeline.addLast(outboundIpTracking);
}
 
Example #6
Source File: NewNettyAcceptor.java    From cassandana with Apache License 2.0 6 votes vote down vote up
private void initializeWebSocketTransport(final NewNettyMQTTHandler handler, Config conf) {
    LOG.debug("Configuring Websocket MQTT transport");
    if(!conf.websocketEnabled) {
    	return;
    }
    
    int port = conf.websocketPort;// Integer.parseInt(webSocketPortProp);

    final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();

    String host = conf.websocketHost;
    initFactory(host, port, "Websocket MQTT", new PipelineInitializer() {

        @Override
        void init(SocketChannel channel) {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new HttpServerCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
            pipeline.addLast("webSocketHandler",
                    new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
            pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
            pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
            configureMQTTPipeline(pipeline, timeoutHandler, handler);
        }
    });
}
 
Example #7
Source File: Http2OrHttpHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.pipeline().addLast(Http2FrameCodecBuilder.forServer().build(), new HelloWorldHttp2Handler());
        return;
    }

    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        ctx.pipeline().addLast(new HttpServerCodec(),
                               new HttpObjectAggregator(MAX_CONTENT_LENGTH),
                               new HelloWorldHttp1Handler("ALPN Negotiation"));
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}
 
Example #8
Source File: WebSocketServerInitializer.java    From SpringMVC-Project with MIT License 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    //添加闲置处理,60秒没有数据传输,触发事件
    pipeline.addLast(new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
    //将字节解码为HttpMessage对象,并将HttpMessage对象编码为字节
    pipeline.addLast(new HttpServerCodec());
    //出站数据压缩
    pipeline.addLast(new HttpContentCompressor());
    //聚合多个HttpMessage为单个FullHttpRequest
    pipeline.addLast(new HttpObjectAggregator(64 * 1024));
    //如果被请求的端点是/ws,则处理该升级握手
    pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
    //聊天消息处理
    pipeline.addLast(new ChatServerHandler());
    //心跳处理
    pipeline.addLast(new HeartbeatHandler());
}
 
Example #9
Source File: RpcxProcessHandler.java    From rpcx-java with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    if (in.readableBytes() < 1) {
        return;
    }

    final int magic = in.getByte(in.readerIndex());
    ChannelPipeline p = ctx.pipeline();
    //处理http
    if (isHttp(magic)) {
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new RpcxHttpHandler(nettyServer));
        p.remove(this);
    } else {//处理二进制
        p.addLast(new NettyEncoder());
        p.addLast(new NettyDecoder());
        p.addLast(new IdleStateHandler(0, 0, serverChannelMaxIdleTimeSeconds));
        p.addLast(new NettyConnetManageHandler(nettyServer));
        p.addLast(new NettyServerHandler(nettyServer));
        p.remove(this);
    }

}
 
Example #10
Source File: WebSocketServerInitializer.java    From litchi with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpServerCodec());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new WebSocketServerCompressionHandler());
    pipeline.addLast(new IdleStateHandler(0, 0, 60));
    pipeline.addLast(new WebSocketServerProtocolHandler(WEB_SOCKET_PATH, null, true));
    pipeline.addLast(new WebSocketHandler(litchi));

    for (ChannelHandler handler : handlers) {
        pipeline.addLast(handler);
    }
}
 
Example #11
Source File: Server.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #12
Source File: WebSocketServerInitializer.java    From withme3.0 with MIT License 6 votes vote down vote up
@Override
    protected void initChannel(SocketChannel e) throws Exception {

        //protobuf处理器
//        e.pipeline().addLast("frameDecoder", new ProtobufVarint32FrameDecoder());//用于Decode前解决半包和粘包问题
        //此处需要传入自定义的protobuf的defaultInstance
        // e.pipeline().addLast("protobufDecoder",new ProtobufDecoder();
        //将请求和应答消息解码为http消息
        e.pipeline().addLast("http-codec", new HttpServerCodec());
        //HttpObjectAggregator:将Http消息的多个部分合成一条完整的消息
        e.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
        //ChunkedWriteHandler:向客户端发送HTML5文件
        e.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
        //在管道中添加我们自己实现的接收数据实现方法
        e.pipeline().addLast("handler", new WebSocketServerHandler());

    }
 
Example #13
Source File: HttpRequestInitializer.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   pipeline.addLast(inboundIpTracking);

   if (serverTlsContext != null && serverTlsContext.useTls()) {
      SSLEngine engine = serverTlsContext.getContext().newEngine(ch.alloc());
      engine.setNeedClientAuth(serverConfig.isTlsNeedClientAuth());
      engine.setUseClientMode(false);
      pipeline.addLast(FILTER_SSL, new SslHandler(engine));
   }

   pipeline.addLast(FILTER_CODEC, new HttpServerCodec());
   pipeline.addLast(FILTER_HTTP_AGGREGATOR, new HttpObjectAggregator(65536));
   pipeline.addLast("bind-client-context", oauthBindClientContext);
   pipeline.addLast(FILTER_HANDLER, handlerProvider.get());
   pipeline.addLast(outboundIpTracking);
}
 
Example #14
Source File: HttpProxyServer.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();
    switch (testMode) {
    case INTERMEDIARY:
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1));
        p.addLast(new HttpIntermediaryHandler());
        break;
    case TERMINAL:
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1));
        p.addLast(new HttpTerminalHandler());
        break;
    case UNRESPONSIVE:
        p.addLast(UnresponsiveHandler.INSTANCE);
        break;
    }
}
 
Example #15
Source File: HttpRequestInitializer.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   VIDEO_CONNECTIONS.inc();

   pipeline.addLast(new IPTrackingInboundHandler());
   if (serverTlsContext != null && serverTlsContext.useTls()) {
      SSLEngine engine = serverTlsContext.getContext().newEngine(ch.alloc());
      engine.setNeedClientAuth(serverConfig.isTlsNeedClientAuth());
      engine.setUseClientMode(false);

      SslHandler handler = new SslHandler(engine);
      handler.setHandshakeTimeout(videoConfig.getVideoSslHandshakeTimeout(), TimeUnit.SECONDS);
      handler.setCloseNotifyTimeout(videoConfig.getVideoSslCloseNotifyTimeout(), TimeUnit.SECONDS);

      pipeline.addLast(FILTER_SSL, handler);
   }

   pipeline.addLast(FILTER_CODEC, new HttpServerCodec());
   pipeline.addLast(FILTER_HTTP_AGGREGATOR, new HttpObjectAggregator(videoConfig.getVideoHttpMaxContentLength()));
   pipeline.addLast(FILTER_HANDLER, channelInboundProvider.get());
   pipeline.addLast(new IPTrackingOutboundHandler());

   ch.pipeline().addAfter(FILTER_HTTP_AGGREGATOR, "corshandler", new CorsHandler(corsConfig.build()));

}
 
Example #16
Source File: Http2OrHttpHandler.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.pipeline().addLast(new Http2HandlerBuilder().build());
        return;
    }

    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        ctx.pipeline().addLast(new HttpServerCodec(),
                new HttpObjectAggregator(MAX_CONTENT_LENGTH),
                new Http1Handler("ALPN Negotiation"));
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}
 
Example #17
Source File: HttpServerChannelInitializer.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
   Preconditions.checkNotNull(handler, "Must specify a channel handler");
   
   ChannelPipeline pipeline = ch.pipeline();
   pipeline.addLast(new HttpServerCodec());
   if(maxRequestSizeBytes > 0) {
      pipeline.addLast(new HttpObjectAggregator(maxRequestSizeBytes));
   }
   if(chunkedWrites) {
      pipeline.addLast(new ChunkedWriteHandler());
   }
   if(clientFactory != null) {
      pipeline.addLast(new BindClientContextHandler(cookieConfig, clientFactory, requestAuthorizer));
   }
   pipeline.addLast(handler);
}
 
Example #18
Source File: InboundWebsocketChannelInitializer.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel websocketChannel) throws Exception {

    if (sslConfiguration != null) {
        SslHandler sslHandler = new SSLHandlerFactory(sslConfiguration).create();
        websocketChannel.pipeline().addLast("ssl", sslHandler);
    }

    ChannelPipeline p = websocketChannel.pipeline();
    p.addLast("codec", new HttpServerCodec());
    p.addLast("aggregator", new HttpObjectAggregator(65536));
    p.addLast("frameAggregator", new WebSocketFrameAggregator(Integer.MAX_VALUE));
    InboundWebsocketSourceHandler sourceHandler = new InboundWebsocketSourceHandler();
    sourceHandler.setClientBroadcastLevel(clientBroadcastLevel);
    sourceHandler.setDispatchToCustomSequence(dispatchToCustomSequence);
    sourceHandler.setPortOffset(portOffset);
    if (outflowDispatchSequence != null)
        sourceHandler.setOutflowDispatchSequence(outflowDispatchSequence);
    if (outflowErrorSequence != null)
        sourceHandler.setOutflowErrorSequence(outflowErrorSequence);
    if (subprotocolHandlers != null)
        sourceHandler.setSubprotocolHandlers(subprotocolHandlers);
    if (pipelineHandler != null)
        p.addLast("pipelineHandler", pipelineHandler.getClass().getConstructor().newInstance());
    p.addLast("handler", sourceHandler);
}
 
Example #19
Source File: Http2OrHttpHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.pipeline().addLast(Http2MultiplexCodecBuilder.forServer(new HelloWorldHttp2Handler()).build());
        return;
    }

    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        ctx.pipeline().addLast(new HttpServerCodec(),
                               new HttpObjectAggregator(MAX_CONTENT_LENGTH),
                               new HelloWorldHttp1Handler("ALPN Negotiation"));
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}
 
Example #20
Source File: NettyAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void pipelineAddExit(final Object thiz, final Object arg2) {
  final ChannelPipeline pipeline = (ChannelPipeline)thiz;
  final ChannelHandler handler = (ChannelHandler)arg2;

  try {
    // Server
    if (handler instanceof HttpServerCodec) {
      pipeline.addLast(TracingHttpServerHandler.class.getName(), new TracingHttpServerHandler());
    }
    else if (handler instanceof HttpRequestDecoder) {
      pipeline.addLast(TracingServerChannelInboundHandlerAdapter.class.getName(), new TracingServerChannelInboundHandlerAdapter());
    }
    else if (handler instanceof HttpResponseEncoder) {
      pipeline.addLast(TracingServerChannelOutboundHandlerAdapter.class.getName(), new TracingServerChannelOutboundHandlerAdapter());
    }
    else
    // Client
    if (handler instanceof HttpClientCodec) {
      pipeline.addLast(TracingHttpClientTracingHandler.class.getName(), new TracingHttpClientTracingHandler());
    }
    else if (handler instanceof HttpRequestEncoder) {
      pipeline.addLast(TracingClientChannelOutboundHandlerAdapter.class.getName(), new TracingClientChannelOutboundHandlerAdapter());
    }
    else if (handler instanceof HttpResponseDecoder) {
      pipeline.addLast(TracingClientChannelInboundHandlerAdapter.class.getName(), new TracingClientChannelInboundHandlerAdapter());
    }
  }
  catch (final IllegalArgumentException ignore) {
  }
}
 
Example #21
Source File: WebsocketHandlerBuilder.java    From hxy-socket with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void buildChannelPipeline(ChannelPipeline pipeline) {
    pipeline.addLast(new HttpServerCodec());
    pipeline.addLast(new HttpServerExpectContinueHandler());
    pipeline.addLast(MsgOutboundHandler.INSTANCE);
    if(socketConfiguration.getProtocolType() == SocketConfiguration.ProtocolType.TEXT){
        pipeline.addLast(new DefaultTextWebSocketServerHandler());
    }else{
        pipeline.addLast(new ProtocolWebSocketServerHandler());
    }
}
 
Example #22
Source File: NettyITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws InterruptedException {
  final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
  final EventLoopGroup workerGroup = new NioEventLoopGroup();
  try {
    final ServerBootstrap bootstrap = new ServerBootstrap()
      .option(ChannelOption.SO_BACKLOG, 1024)
      .group(bossGroup, workerGroup)
      .channel(NioServerSocketChannel.class)
      .handler(new LoggingHandler(LogLevel.INFO))
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel socketChannel) {
          final ChannelPipeline pipeline = socketChannel.pipeline();
          pipeline.addLast(new HttpServerCodec());
          pipeline.addLast(new HttpServerHandler());
        }
      });

    bootstrap.bind(8086).sync().channel();
    client();
  }
  finally {
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
  }

  TestUtil.checkSpan(new ComponentSpanCount("netty", 2, true));
}
 
Example #23
Source File: NettyTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void test(final MockTracer tracer) throws InterruptedException {
  final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
  final EventLoopGroup workerGroup = new NioEventLoopGroup();
  try {
    final ServerBootstrap bootstrap = new ServerBootstrap()
      .option(ChannelOption.SO_BACKLOG, 1024)
      .group(bossGroup, workerGroup)
      .channel(NioServerSocketChannel.class)
      .handler(new LoggingHandler(LogLevel.INFO))
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel socketChannel) {
          final ChannelPipeline pipeline = socketChannel.pipeline();
          pipeline.addLast(new HttpServerCodec());
          pipeline.addLast(new HttpServerHandler());
        }
      });

    bootstrap.bind(8086).sync().channel();
    client();
  }
  finally {
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
  }

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #24
Source File: WsServer.java    From openzaly with Apache License 2.0 5 votes vote down vote up
public WsServer() {
	executor = new SimpleExecutor<Command, CommandResponse>();
	loadExecutor(executor);
	// 负责对外连接线程
	parentGroup = new NioEventLoopGroup();
	// 负责对内分发业务的线程
	childGroup = new NioEventLoopGroup();
	bootstrap = new ServerBootstrap();
	bootstrap.group(parentGroup, childGroup);
	bootstrap.channel(NioServerSocketChannel.class);
	bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			// 30秒空闲时间设置
			ch.pipeline().addLast(new IdleStateHandler(30, 0, 60));
			// HttpServerCodec:将请求和应答消息解码为HTTP消息
			ch.pipeline().addLast(new HttpServerCodec());
			// 针对大文件上传时,把 HttpMessage 和 HttpContent 聚合成一个
			// FullHttpRequest,并定义可以接受的数据大小64M(可以支持params+multipart)
			ch.pipeline().addLast(new HttpObjectAggregator(64 * 1024));
			// 针对大文件下发,分块写数据
			ch.pipeline().addLast(new ChunkedWriteHandler());
			// WebSocket 访问地址
			// ch.pipeline().addLast(new WebSocketServerProtocolHandler("/akaxin/ws"));
			// 自定义handler
			ch.pipeline().addLast(new WsServerHandler(executor));
		}
	});

}
 
Example #25
Source File: Server.java    From cassandra-exporter with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(final SocketChannel ch) {
    ch.pipeline()
            .addLast(new HttpServerCodec())
            .addLast(new HttpObjectAggregator(1048576))
            .addLast(new HttpContentCompressor())
            .addLast(new ChunkedWriteHandler())
            .addLast(new HttpHandler(harvester, helpExposition));
}
 
Example #26
Source File: HttpHelloWorldServerInitializer.java    From netty-learning-example with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    /**
     * 或者使用HttpRequestDecoder & HttpResponseEncoder
     */
    p.addLast(new HttpServerCodec());
    /**
     * 在处理POST消息体时需要加上
     */
    p.addLast(new HttpObjectAggregator(1024*1024));
    p.addLast(new HttpServerExpectContinueHandler());
    p.addLast(new HttpHelloWorldServerHandler());
}
 
Example #27
Source File: NettyRestChannelInitializer.java    From turbo-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
	ch.pipeline()//
			.addLast(new HttpServerCodec(1024 * 4, 1024 * 8, 1024 * 16, false))// HTTP 服务的解码器
			.addLast(new HttpObjectAggregator(TurboConstants.MAX_FRAME_LENGTH))// HTTP 消息的合并处理
			.addLast(new RestHttResponseEncoder(invokerFactory, jsonMapper, filters))// 自定义编码器
			.addLast(new NettyRestHandler(invokerFactory, jsonMapper, filters)); // 逻辑处理
}
 
Example #28
Source File: MyServerInitializer.java    From JerryServer with Apache License 2.0 5 votes vote down vote up
@Override
	public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();  
//        //http-request解码器
//        pipeline.addLast("decoder", new HttpRequestDecoder());
//        //http-response解码器
//        pipeline.addLast("encoder", new HttpResponseEncoder());
//        pipeline.addLast("deflater", new HttpContentCompressor());
//        pipeline.addLast("handler", new MyServerChannelHandler());
        pipeline.addLast(new HttpServerCodec());// HTTP解码器
        pipeline.addLast(new HttpObjectAggregator(65536));// 将多个消息转换为单一的一个FullHttpRequest
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new MyServerChannelHandler());
	}
 
Example #29
Source File: MqttOverWebsocketProtocolHandlerPipeline.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(Channel channel) throws Exception {
    channel.pipeline()
            .addLast(new HttpServerCodec())
            .addLast(new HttpObjectAggregator(65536))
            .addLast(new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST))
            .addLast(new WebSocketFrameToByteBufDecoder())
            .addLast(new ByteBufToWebSocketFrameEncoder())
            .addLast(new MqttDecoder(mqttContext.getMqttConfig().getMaxPayloadSize()))
            .addLast(MqttEncoder.INSTANCE)
            .addLast(new ConnectionHandler())
            .addLast(newMqttCommandInvocation());
}
 
Example #30
Source File: NettyServerForUi.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void start() {
    ServerBootstrap bootstrap = new ServerBootstrap()
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, DEFAULT_WRITE_LOW_WATER_MARK)
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, DEFAULT_WRITE_HIGH_WATER_MARK)
            .channel(NioServerSocketChannel.class)
            .group(BOSS, WORKER)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pip = ch.pipeline();
                    pip.addLast(new IdleStateHandler(0, 0, 30 * 60 * 1000))
                            .addLast(new HttpServerCodec())
                            .addLast(new HttpObjectAggregator(1024 * 1024))
                            .addLast(new WebSocketServerProtocolHandler("/ws"))
                            .addLast(new WebSocketFrameAggregator(1024 * 1024 * 1024))
                            .addLast(new RequestDecoder(new DefaultRequestEncryption(new RSAEncryption())))
                            .addLast(new WebSocketEncoder())
                            .addLast(new TabHandler())
                            .addLast(new HostsValidatorHandler(serverFinder))
                            .addLast(new UiRequestHandler(
                                    commandStore,
                                    uiConnectionStore,
                                    agentConnectionStore,
                                    sessionManager));
                }
            });
    try {
        this.channel = bootstrap.bind(port).sync().channel();
        logger.info("client server startup successfully, port {}", port);
    } catch (Exception e) {
        logger.error("netty server for ui start fail", e);
        throw Throwables.propagate(e);
    }
}