Java Code Examples for io.netty.channel.ChannelPipeline

The following are top voted examples for showing how to use io.netty.channel.ChannelPipeline. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: fresco_floodlight   File: RPCChannelInitializer.java   View source code 7 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
    RPCChannelHandler channelHandler = 
            new RPCChannelHandler(syncManager, rpcService);

    IdleStateHandler idleHandler = 
            new IdleStateHandler(5, 10, 0);
    ReadTimeoutHandler readTimeoutHandler = 
            new ReadTimeoutHandler(30);
    
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("idle", idleHandler);
    pipeline.addLast("timeout", readTimeoutHandler);
    pipeline.addLast("handshaketimeout",
                     new HandshakeTimeoutHandler(channelHandler, timer, 10));

    pipeline.addLast("syncMessageDecoder",
                     new SyncMessageDecoder(maxFrameSize));
    pipeline.addLast("syncMessageEncoder",
                     new SyncMessageEncoder());

    pipeline.addLast("handler", channelHandler);
}
 
Example 2
Project: tasfe-framework   File: HttpChannelInitializer.java   View source code 7 votes vote down vote up
public final ChannelPipeline appendHttpPipeline(ChannelPipeline channelPipeline) {
    // 服务端,对响应编码。属于ChannelOutboundHandler,逆序执行
    channelPipeline.addLast("encoder", new HttpResponseEncoder());

    // 服务端,对请求解码。属于ChannelIntboundHandler,按照顺序执行
    channelPipeline.addLast("decoder", new HttpRequestDecoder());
    //即通过它可以把 HttpMessage 和 HttpContent 聚合成一个 FullHttpRequest,并定义可以接受的数据大小,在文件上传时,可以支持params+multipart
    channelPipeline.addLast("aggregator", new HttpObjectAggregator(maxConentLength));
    //块写入写出Handler
    channelPipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

    // 对传输数据进行压缩,这里在客户端需要解压缩处理
    // channelPipeline.addLast("deflater", new HttpContentCompressor());

    HttpServletHandler servletHandler = new HttpServletHandler();
    servletHandler.addInterceptor(new ChannelInterceptor());
    //servletHandler.addInterceptor(new HttpSessionInterceptor(getHttpSessionStore()));
    // 自定义Handler
    channelPipeline.addLast("handler", servletHandler);
    // 异步
    // channelPipeline.addLast(businessExecutor, new AsyncHttpServletHandler());
    return channelPipeline;
}
 
Example 3
Project: fresco_floodlight   File: OFChannelHandler.java   View source code 6 votes vote down vote up
/**
 * Creates a handler for interacting with the switch channel
 *
 * @param controller
 *            the controller
 * @param newConnectionListener
 *            the class that listens for new OF connections (switchManager)
 * @param pipeline
 *            the channel pipeline
 * @param threadPool
 *            the thread pool
 * @param idleTimer
 *            the hash wheeled timer used to send idle messages (echo).
 *            passed to constructor to modify in case of aux connection.
 * @param debugCounters
 */
OFChannelHandler(@Nonnull IOFSwitchManager switchManager,
		@Nonnull INewOFConnectionListener newConnectionListener,
		@Nonnull ChannelPipeline pipeline,
		@Nonnull IDebugCounterService debugCounters,
		@Nonnull Timer timer,
		@Nonnull List<U32> ofBitmaps,
		@Nonnull OFFactory defaultFactory) {

	Preconditions.checkNotNull(switchManager, "switchManager");
	Preconditions.checkNotNull(newConnectionListener, "connectionOpenedListener");
	Preconditions.checkNotNull(pipeline, "pipeline");
	Preconditions.checkNotNull(timer, "timer");
	Preconditions.checkNotNull(debugCounters, "debugCounters");

	this.pipeline = pipeline;
	this.debugCounters = debugCounters;
	this.newConnectionListener = newConnectionListener;
	this.counters = switchManager.getCounters();
	this.state = new InitState();
	this.timer = timer;
	this.ofBitmaps = ofBitmaps;
	this.factory = defaultFactory;

	log.debug("constructor on OFChannelHandler {}", String.format("%08x", System.identityHashCode(this)));
}
 
Example 4
Project: Quavo   File: WorldLoginListener.java   View source code 6 votes vote down vote up
@Override
public void handleMessage(ChannelHandlerContext ctx, WorldLoginRequest msg) {
	ClientMessage message = evaluateLogin(msg);
	if (message != ClientMessage.SUCCESSFUL) {
		ctx.write(new WorldLoginResponse(message));
		return;
	}

	Player player = new Player(ctx.channel());
	ctx.write(new WorldLoginResponse(player, message, msg.getIsaacPair()));

	ChannelPipeline pipeline = ctx.pipeline();
	pipeline.remove("login.encoder");

	// this isnt set automatically.
	pipeline.addAfter("world.decoder", "game.encoder", new GamePacketEncoder(msg.getIsaacPair().getEncoderRandom()));
	pipeline.replace("world.decoder", "game.decoder", new GamePacketDecoder(player, msg.getIsaacPair().getDecoderRandom()));

	player.init(msg.getDisplayInformation());
}
 
Example 5
Project: push   File: Client.java   View source code 6 votes vote down vote up
public void run() {
	workerGroup = new NioEventLoopGroup();
	try {
		Bootstrap b = new Bootstrap();
		b.group(workerGroup);
		b.channel(NioSocketChannel.class);
		// b.option(ChannelOption.SO_KEEPALIVE, true);
		b.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();
				pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 4));
				pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
				pipeline.addLast("decoder", new MsgPackDecode());
				pipeline.addLast("encoder", new MsgPackEncode());
				pipeline.addLast(new ClientHandler());
			}
		});
		channel = b.connect(clientProperties.getServerHost(), clientProperties.getServerPort()).sync().channel();
		status = Status.START;
		channel.closeFuture().sync();
	} catch (Exception e) {
		e.printStackTrace();
	}
	status = Status.STOP;
}
 
Example 6
Project: push-network-proxies   File: MockingFCMServerInitializer.java   View source code 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();

    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }

    p.addLast(new HttpRequestDecoder());
    // Uncomment the following line if you don't want to handle HttpChunks.
    //p.addLast(new HttpObjectAggregator(1048576));
    p.addLast(new HttpResponseEncoder());
    // Remove the following line if you don't want automatic content compression.
    //p.addLast(new HttpContentCompressor());
    p.addLast(new MockingFCMServerHandler());
}
 
Example 7
Project: graphiak   File: GraphiakInitializer.java   View source code 6 votes vote down vote up
@Override
public void initChannel(final SocketChannel ch) throws Exception {
    final ChannelPipeline p = ch.pipeline();

    // removes idle connections after READER_IDLE_SECONDS seconds
    p.addLast("idleStateHandler",
            new IdleStateHandler(READER_IDLE_SECONDS, 0, 0));

    // handle new connections and idle timeouts
    p.addLast("auth", authHandler);

    // break each data chunk by newlines and split out metrics
    p.addLast("line", new GraphiteMetricDecoder(maxLength));

    // batch up metrics and store
    p.addLast("metrics", new MetricHandler(store));
}
 
Example 8
Project: ZentrelaRPG   File: TinyProtocol.java   View source code 6 votes vote down vote up
private void unregisterChannelHandler() {
    if (serverChannelHandler == null)
        return;

    for (Channel serverChannel : serverChannels) {
        final ChannelPipeline pipeline = serverChannel.pipeline();

        // Remove channel handler
        serverChannel.eventLoop().execute(new Runnable() {

            @Override
            public void run() {
                try {
                    pipeline.remove(serverChannelHandler);
                } catch (NoSuchElementException e) {
                    // That's fine
                }
            }

        });
    }
}
 
Example 9
Project: SamaGamesAPI   File: TinyProtocol.java   View source code 6 votes vote down vote up
private void unregisterChannelHandler() {
    if (serverChannelHandler == null)
        return;

    for (Channel serverChannel : serverChannels) {
        final ChannelPipeline pipeline = serverChannel.pipeline();

        // Remove channel handler
        serverChannel.eventLoop().execute(new Runnable() {

            @Override
            public void run() {
                try {
                    pipeline.remove(serverChannelHandler);
                } catch (NoSuchElementException e) {
                    // That's fine
                }
            }

        });
    }
}
 
Example 10
Project: Quavo   File: ConnectionEncoder.java   View source code 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, ConnectionResponse msg, ByteBuf out) throws Exception {
	ChannelPipeline pipeline = ctx.pipeline();

	switch (msg.getType()) {
	case HANDSHAKE_CONNECTION:
		pipeline.addAfter("decoder", "handshake.encoder", new HandshakeEncoder());
		pipeline.replace("decoder", "handshake.decoder", new HandshakeDecoder());
		break;
	case LOGIN_CONNECTION:
		out.writeByte(ClientMessage.SUCCESSFUL_CONNECTION.getId());
		pipeline.addAfter("decoder", "login.encoder", new LoginEncoder());
		pipeline.replace("decoder", "login.decoder", new LoginDecoder());
		break;
	}

	pipeline.remove(this);
}
 
Example 11
Project: iotplatform   File: MqttTransportServerInitializer.java   View source code 6 votes vote down vote up
@Override
  public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    SslHandler sslHandler = null;
    if (sslHandlerProvider != null) {
      sslHandler = sslHandlerProvider.getSslHandler();
      pipeline.addLast(sslHandler);
    }
    pipeline.addLast("decoder", new MqttDecoder(MAX_PAYLOAD_SIZE));
    pipeline.addLast("encoder", MqttEncoder.INSTANCE);

    MqttTransportHandler handler = new MqttTransportHandler(msgProducer, deviceService, authService, assetService,
        assetAuthService, relationService, sslHandler);
    pipeline.addLast(handler);

//    ch.closeFuture().addListener(handler);

  }
 
Example 12
Project: ClusterDeviceControlPlatform   File: ConfigHandler.java   View source code 6 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);
    logger.info("通道重置");
    List<ChannelPipeline> channelPipelines = tcpMediator.getSendingMsgRepo().getChannelPipelines();
    channelPipelines.add(ctx.pipeline());
    channelPipelines.removeIf(channel -> {
        i++;
        if (channel == null || !channel.channel().isActive()) {
            logger.info("「" + i + "」" + "通道失效");
            return true;
        } else {
            logger.info("「" + i + "」" + "通道有效");
            return false;
        }
    });
    i = 0;
    logger.info("通道数量:" + channelPipelines.size());
}
 
Example 13
Project: util4j   File: HttpServerInitHandler.java   View source code 6 votes vote down vote up
@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline p = ch.pipeline();
		if(sslCtx!=null)
		{
			p.addLast(new SslHandler(sslCtx.newEngine(ch.alloc())));
		}
		p.addLast(new HttpResponseEncoder());//必须放在最前面,如果decoder途中需要回复消息,则decoder前面需要encoder
		p.addLast(new HttpRequestDecoder());
		p.addLast(new HttpObjectAggregator(65536));//限制contentLength
		//大文件传输处理
//		p.addLast(new ChunkedWriteHandler());
//		p.addLast(new HttpContentCompressor());
		//跨域配置
		CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
		p.addLast(new CorsHandler(corsConfig));
		p.addLast(new DefaultListenerHandler<HttpRequest>(listener));
	}
 
Example 14
Project: jsf-sdk   File: ClientChannelInitializer.java   View source code 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    // 根据服务端协议,选择解码器
    Constants.ProtocolType type = transportConfig.getProvider().getProtocolType();
    switch (type) {
        case jsf:
            pipeline.addLast(new JSFEncoder());
            pipeline.addLast(new JSFDecoder(transportConfig.getPayload()));
            break;
        case dubbo:
            pipeline.addLast(new DubboEncoder());
            pipeline.addLast(new DubboDecoder(transportConfig.getPayload()));
            break;
        default:
            throw new InitErrorException("Unsupported client protocol type : " + type.name());
    }
    pipeline.addLast(Constants.CLIENT_CHANNELHANDLE_NAME, clientChannelHandler);
}
 
Example 15
Project: reactive-pg-client   File: SocketConnection.java   View source code 6 votes vote down vote up
void initiateProtocolOrSsl(String username, String password, String database, Handler<? super CommandResponse<Connection>> completionHandler) {
  ChannelPipeline pipeline = socket.channelHandlerContext().pipeline();
  if (ssl) {
    Future<Void> upgradeFuture = Future.future();
    upgradeFuture.setHandler(ar -> {
      if (ar.succeeded()) {
        initiateProtocol(username, password, database, completionHandler);
      } else {
        Throwable cause = ar.cause();
        if (cause instanceof DecoderException) {
          DecoderException err = (DecoderException) cause;
          cause = err.getCause();
        }
        completionHandler.handle(CommandResponse.failure(cause));
      }
    });
    pipeline.addBefore("handler", "initiate-ssl-handler", new InitiateSslHandler(this, upgradeFuture));
  } else {
    initiateProtocol(username, password, database, completionHandler);
  }
}
 
Example 16
Project: happylifeplat-transaction   File: NettyServerHandlerInitializer.java   View source code 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    final ChannelPipeline pipeline = ch.pipeline();
    NettyPipelineInit.serializePipeline(serializeProtocolEnum, pipeline);
    pipeline.addLast("timeout",
            new IdleStateHandler(nettyConfig.getHeartTime(), nettyConfig.getHeartTime(), nettyConfig.getHeartTime(), TimeUnit.SECONDS));
    pipeline.addLast(nettyServerMessageHandler);
}
 
Example 17
Project: happylifeplat-transaction   File: NettyClientHandlerInitializer.java   View source code 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    final ChannelPipeline pipeline = socketChannel.pipeline();
    NettyPipelineInit.serializePipeline(serializeProtocolEnum, pipeline);
    pipeline.addLast("timeout", new IdleStateHandler(txConfig.getHeartTime(), txConfig.getHeartTime(), txConfig.getHeartTime(), TimeUnit.SECONDS));
    pipeline.addLast(nettyClientMessageHandler);

}
 
Example 18
Project: cr-private-server   File: PlayerInitializer.java   View source code 5 votes vote down vote up
@Override
public void initChannel(SocketChannel channel) throws Exception {
	ClientCrypto clientCrypto = new ClientCrypto(NetworkServer.SERVER_KEY);
	ServerCrypto serverCrypto = new ServerCrypto();

	clientCrypto.setServer(serverCrypto);
	serverCrypto.setClient(clientCrypto);

	ChannelPipeline pipeline = channel.pipeline();
	pipeline.addLast(new PacketDecoder(serverCrypto));
	pipeline.addLast(new PacketEncoder(serverCrypto));
	pipeline.addLast(new PlayerHandler(server));
}
 
Example 19
Project: GitHub   File: NettyHttpClient.java   View source code 5 votes vote down vote up
@Override public void prepare(final Benchmark benchmark) {
  this.concurrencyLevel = benchmark.concurrencyLevel;
  this.targetBacklog = benchmark.targetBacklog;

  ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
    @Override public void initChannel(SocketChannel channel) throws Exception {
      ChannelPipeline pipeline = channel.pipeline();

      if (benchmark.tls) {
        SslClient sslClient = SslClient.localhost();
        SSLEngine engine = sslClient.sslContext.createSSLEngine();
        engine.setUseClientMode(true);
        pipeline.addLast("ssl", new SslHandler(engine));
      }

      pipeline.addLast("codec", new HttpClientCodec());
      pipeline.addLast("inflater", new HttpContentDecompressor());
      pipeline.addLast("handler", new HttpChannel(channel));
    }
  };

  bootstrap = new Bootstrap();
  bootstrap.group(new NioEventLoopGroup(concurrencyLevel))
      .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
      .channel(NioSocketChannel.class)
      .handler(channelInitializer);
}
 
Example 20
Project: sctalk   File: NettyChatServerInitializer.java   View source code 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast("framer", new LengthFieldBasedFrameDecoder(400 * 1024, 0, 4, -4, 0));
    pipeline.addLast("decoder", new PacketDecoder());
    pipeline.addLast("encoder", new PacketEncoder());
    pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
    pipeline.addLast("handler", new MessageServerHandler(handlerManager));
}
 
Example 21
Project: Quavo   File: NetworkMessageHandler.java   View source code 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, NetworkMessage msg) throws Exception {
	NetworkMessageListener<NetworkMessage> listener = NetworkMessageRepository.getNetworkListener(msg);

	listener.handleMessage(ctx, msg);

	ChannelPipeline pipeline = ctx.pipeline();
	ChannelHandler handler = msg.getHandler();

	if (pipeline.context(handler) != null) {

		// flush for specific handler.
		pipeline.context(handler).flush();
	}
}
 
Example 22
Project: Ashbringer-load   File: HttpClientInitializer.java   View source code 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {

    ChannelPipeline p = ch.pipeline();

    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }
    p.addLast(new HttpClientCodec());
}
 
Example 23
Project: TakinRPC   File: ClientInitializer.java   View source code 5 votes vote down vote up
@Override
protected void initChannel(T ch) throws Exception {
    ChannelPipeline p = ch.pipeline();

    p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
    p.addLast("protobufDecoder", new ProtobufDecoder(NettyRpcProto.RpcContainer.getDefaultInstance()));

    p.addLast("frameEncoder", new LengthFieldPrepender(4));
    p.addLast("protobufEncoder", new ProtobufEncoder());

    ConcurrentHashMap<Integer, RpcCall> callMap = new ConcurrentHashMap<Integer, RpcCall>();
    p.addLast(eventExecutor, "inboundHandler", new InboundHandler(callMap));
    p.addLast("outboundHandler", new OutboundHandler(callMap));

}
 
Example 24
Project: TakinRPC   File: ServerInitializer.java   View source code 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();

    p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
    p.addLast("protobufDecoder", new ProtobufDecoder(NettyRpcProto.RpcContainer.getDefaultInstance()));

    p.addLast("frameEncoder", new LengthFieldPrepender(4));
    p.addLast("protobufEncoder", new ProtobufEncoder());

    p.addLast(eventExecutor, "serverHandler", handler);
}
 
Example 25
Project: os   File: WebSocketServerInitializer.java   View source code 5 votes vote down vote up
protected void initChannel(NioSocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    // 编解码 http 请求
    pipeline.addLast(new HttpServerCodec());
    // 写文件内容
    pipeline.addLast(new ChunkedWriteHandler());
    // 聚合解码 HttpRequest/HttpContent/LastHttpContent 到 FullHttpRequest
    // 保证接收的 Http 请求的完整性
    pipeline.addLast(new HttpObjectAggregator(64 * 1024));
    // 处理其他的 WebSocketFrame
    pipeline.addLast(new WebSocketServerProtocolHandler("/chat"));
    // 处理 TextWebSocketFrame
    pipeline.addLast(protoCodec);
    pipeline.addLast(serverHandler);
}
 
Example 26
Project: sctalk   File: NettyWebServerInitializer.java   View source code 5 votes vote down vote up
@Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        logger.info("******", pipeline.toString());
        pipeline.addLast("http-codec", new HttpServerCodec());
        pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); // Http消息组装  
        pipeline.addLast("http-chunked", new ChunkedWriteHandler()); // WebSocket通信支持  
        pipeline.addLast("framer", new LengthFieldBasedFrameDecoder(400 * 1024, 0, 4, -4, 0));
//        pipeline.addLast("decoder", new PacketDecoder());
//        pipeline.addLast("encoder", new PacketEncoder());
        pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
        pipeline.addLast("handler", new MessageSocketServerHandler(handlerManager));
    }
 
Example 27
Project: cornerstone   File: HttpHelloWorldServerInitializer.java   View source code 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    p.addLast(new HttpServerCodec());
    p.addLast(new HttpRequestDecoder());
    p.addLast(new HttpObjectAggregator(20248));
    p.addLast(new VINettyHandler());
    p.addLast(new HttpHelloWorldServerHandler());
}
 
Example 28
Project: CustomWorldGen   File: FMLNetworkHandler.java   View source code 5 votes vote down vote up
@SideOnly(Side.CLIENT)
private static void addClientHandlers()
{
    ChannelPipeline pipeline = channelPair.get(Side.CLIENT).pipeline();
    String targetName = channelPair.get(Side.CLIENT).findChannelHandlerNameForType(FMLRuntimeCodec.class);
    pipeline.addAfter(targetName, "GuiHandler", new OpenGuiHandler());
    pipeline.addAfter(targetName, "EntitySpawnHandler", new EntitySpawnHandler());
}
 
Example 29
Project: neto   File: ProtocolUnificationHandler.java   View source code 5 votes vote down vote up
private void switchToHttp(ChannelHandlerContext ctx) {
    ChannelPipeline p = ctx.pipeline();
    p.addLast(new HttpServerCodec());
    p.addLast(new HttpObjectAggregator(65536));
    p.addLast(new WebSocketServerCompressionHandler());
    p.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, "ws", true));
    p.addLast(new NetoJsonStringToMapWebSocketDecoder());
    p.addLast(new NetoMessageToWebsocketFrameEncoder());
    p.remove(this);

    // 핸들러를 다시 등록 했으므로 이벤트를 전파
    ctx.fireChannelActive();
}
 
Example 30
Project: tcp-gateway   File: ServerChannelInitializer.java   View source code 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ProtobufAdapter adapter = new ProtobufAdapter(config);

    ChannelPipeline pipeline = socketChannel.pipeline();
    pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
    pipeline.addLast("decoder", adapter.getDecoder());
    pipeline.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
    pipeline.addLast("encoder", adapter.getEncoder());
    pipeline.addLast("handler", new TcpServerHandler(config));
}
 
Example 31
Project: mqttserver   File: TcpChannelInitializer.java   View source code 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
	ChannelPipeline pipeline = ch.pipeline();
	pipeline.addLast("encoder", new MqttMessageEncoder());
	pipeline.addLast("decoder", new MqttMessageDecoder());
	pipeline.addLast("handler", new MqttMessageHandler());
}
 
Example 32
Project: GoPush   File: NodeServerBootstrap.java   View source code 5 votes vote down vote up
@PostConstruct
public void start() throws Exception {

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workGroup)
            .channelFactory(NioServerSocketChannel::new)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                    pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
                    pipeline.addLast("idleStateHandler", new IdleStateHandler(300, 0, 0));
                    pipeline.addLast("handler", nodeChannelInBoundHandler);
                }
            })
            .option(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_SNDBUF, 2048)
            .option(ChannelOption.SO_RCVBUF, 1024);
    bootstrap.bind(goPushNodeServerConfig.getNodePort()).sync();
    log.info("Node server start successful! listening port: {}", goPushNodeServerConfig.getNodePort());
}
 
Example 33
Project: GoPush   File: DeviceServerBootstrap.java   View source code 5 votes vote down vote up
@PostConstruct
public void start() throws Exception {


    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workGroup)
            .channelFactory(NioServerSocketChannel::new)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast("logHandler", new LoggingHandler());
                    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                    pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
                    pipeline.addLast("idleStateHandler", new IdleStateHandler(300, 0, 0));

                    pipeline.addLast("handler", deviceChannelInboundHandler);
                }
            })

            .option(ChannelOption.SO_BACKLOG, 1000000)  //连接队列深度
            .option(ChannelOption.TCP_NODELAY, true)   //设置 no_delay
            .option(ChannelOption.SO_SNDBUF, 2048).option(ChannelOption.SO_RCVBUF, 1024)
            .childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_SNDBUF, 2048).childOption(ChannelOption.SO_RCVBUF, 1024)
            .childOption(ChannelOption.SO_LINGER, 0);

    bootstrap.bind(goPushNodeServerConfig.getDevicePort()).sync();
    log.info("device server start successful! listening port: {}", goPushNodeServerConfig.getDevicePort());
}
 
Example 34
Project: tasfe-framework   File: NettyEmbeddedServletInitializer.java   View source code 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();
    p.addLast("codec", new HttpServerCodec(4096, 8192, 8192, false));
    p.addLast("servletInput", new ServletContentHandler(servletContext));
    p.addLast(servletExecutor, "filterChain", requestDispatcherHandler);
}
 
Example 35
Project: tasfe-framework   File: HttpChannelInitializer.java   View source code 5 votes vote down vote up
@Override
 protected void initChannel(SocketChannel ch) throws Exception {
     ChannelPipeline pipeline = ch.pipeline();

     // SSL的安全链接
     if (ServerConfig.isSsl()) {
         SSLContext sslcontext = SSLContext.getInstance("TLS");
         KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
         KeyStore ks = KeyStore.getInstance("JKS");
         String keyStorePath = ServerConfig.getKeyStorePath();
         String keyStorePassword = ServerConfig.getKeyStorePassword();
         ks.load(new FileInputStream(keyStorePath), keyStorePassword.toCharArray());
         String keyPassword = ServerConfig.getKeyPassword();
         kmf.init(ks, keyPassword.toCharArray());
         sslcontext.init(kmf.getKeyManagers(), null, null);
         SSLEngine sslEngine = sslcontext.createSSLEngine();
         sslEngine.setUseClientMode(false);
         sslEngine.setNeedClientAuth(false);
         /**
          * 务必放在第一位
          */
         pipeline.addLast(new SslHandler(sslEngine));
         logger.info("initChannel: addLast SslHandler");
         /**
          * Generates a temporary self-signed certificate for testing purposes.
          */
/*SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
//SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
if (sslCtx != null) {
	pipeline.addLast(sslCtx.newHandler(ch.alloc()));
}*/
     }
     // Register HTTP handler chain.
     this.appendHttpPipeline(pipeline);
 }
 
Example 36
Project: hekate   File: NettyClient.java   View source code 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
    connectComplete = true;

    if (future.isSuccess()) {
        if (future.channel().isOpen()) {
            if (trace) {
                log.trace("Channel connect future completed successfully [to={}]", id);
            }
        } else {
            // Channel was disconnect()'ed while we were connecting.
            becomeDisconnected();
        }
    } else if (firstError == null) {
        if (trace) {
            log.trace("Notifying on connect future failure [to={}]", id, future.cause());
        }

        firstError = NettyErrorUtils.unwrap(future.cause());

        ChannelPipeline pipeline = future.channel().pipeline();

        if (pipeline.names().contains(NettyClientStateHandler.class.getName())) {
            pipeline.fireExceptionCaught(firstError);
        } else {
            becomeDisconnected();
        }
    }
}
 
Example 37
Project: hekate   File: NettyServerClient.java   View source code 5 votes vote down vote up
public NettyServerClient(InetSocketAddress remoteAddress, InetSocketAddress localAddress, boolean ssl, int hbInterval,
    int hbLossThreshold, boolean hbDisabled, Map<String, HandlerRegistration> handlers, EventLoopGroup coreEventLoopGroup) {
    this.remoteAddress = remoteAddress;
    this.localAddress = localAddress;
    this.ssl = ssl;
    this.hbInterval = hbInterval;
    this.hbLossThreshold = hbLossThreshold;
    this.hbDisabled = hbDisabled;
    this.handlers = handlers;
    this.coreEventLoopGroup = coreEventLoopGroup;

    writeListener = future -> {
        if (future.isSuccess()) {
            // Notify metrics on successful operation.
            if (metrics != null) {
                metrics.onMessageDequeue();

                metrics.onMessageSent();
            }
        } else {
            ChannelPipeline pipeline = future.channel().pipeline();

            // Notify on error (only if pipeline is not empty).
            if (pipeline.last() != null) {
                future.channel().pipeline().fireExceptionCaught(future.cause());
            }

            // Notify metrics on failed operation.
            if (metrics != null) {
                metrics.onMessageDequeue();

                metrics.onMessageSendError();
            }
        }
    };

    hbFlushListener = future -> hbFlushed = true;
}
 
Example 38
Project: uavstack   File: AbstractHttpServiceComponent2.java   View source code 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {

    ChannelPipeline pipeline = socketChannel.pipeline();
    pipeline.addLast(new HttpServerCodec());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new DefaultHttpServerHandler(ahsc));
}
 
Example 39
Project: netty-socks   File: SSocksUpstream.java   View source code 5 votes vote down vote up
@Override
public void initChannel(SocketChannel channel) {
    ChannelPipeline pipeline = channel.pipeline();

    Address upstreamAddress = getAddress();
    SocketAddress address = new InetSocketAddress(upstreamAddress.getHost(), upstreamAddress.getPort());
    pipeline.addFirst(HANDLER_NAME, new SSocksConnectHandler(channel.newPromise(), address, cipher, password));
}
 
Example 40
Project: netty-socks   File: Socks5Upstream.java   View source code 5 votes vote down vote up
@Override
public void initChannel(SocketChannel channel) {
    ChannelPipeline pipeline = channel.pipeline();

    Address upstreamAddress = getAddress();
    SocketAddress address = new InetSocketAddress(upstreamAddress.getHost(), upstreamAddress.getPort());
    pipeline.addFirst(HANDLER_NAME, new Socks5ProxyHandler(address));
}