下面列出了io.netty.channel.ChannelDuplexHandler#io.netty.handler.logging.LoggingHandler 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void initChannel(SocketChannel socketChannel) {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline
// log
.addLast("logging", new LoggingHandler(LogLevel.INFO))
// 心跳检测
// .addLast(new IdleStateHandler(10, 0, 0, TimeUnit.SECONDS))
// .addLast(new HeartBeatHandler())
// 链路管理
.addLast(new ChannelManagerHandler())
;
// 拓展
extHandler(socketChannel.pipeline());
pipeline.addLast(new MqHandler())
// 异常管理
.addLast(new ExceptionHandler())
;
}
public void setLoggingEnabled(boolean enabled) {
checkState(initialized, "Not initialized.");
if (channelFuture == null) {
LOG.debug("No channel future available, doing nothing.");
return;
}
ChannelPipeline pipeline = channelFuture.channel().pipeline();
if (enabled && pipeline.get(LOGGING_HANDLER_NAME) == null) {
pipeline.addFirst(LOGGING_HANDLER_NAME,
new LoggingHandler(RxtxClientChannelManager.this.getClass()));
} else if (!enabled && pipeline.get(LOGGING_HANDLER_NAME) != null) {
pipeline.remove(LOGGING_HANDLER_NAME);
}
}
public static void main(String[] args) throws Exception {
ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));
EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new CustomProtocolInitializer(maxPayloadSize));
ChannelFuture f = b.bind(PORT);
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));
EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new GatewayTransportServerInitializer(maxPayloadSize));
ChannelFuture f = b.bind(PORT);
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));
EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new MqttTransportServerInitializer(maxPayloadSize));
ChannelFuture f = b.bind(PORT);
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private Channel tcpServer(int port) throws Exception {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(this.bossGroup, this.workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline channelPipeline = socketChannel.pipeline();
channelPipeline.addFirst("idle", new IdleStateHandler(
0,
0,
weEventConfig.getKeepAlive()));
//channelPipeline.addLast("ssl", getSslHandler(sslContext, socketChannel.alloc()));
channelPipeline.addLast("decoder", new MqttDecoder());
channelPipeline.addLast("encoder", MqttEncoder.INSTANCE);
channelPipeline.addLast("broker", new TcpHandler(protocolProcess));
}
});
return serverBootstrap.bind(port).sync().channel();
}
ChannelFuture bing() {
ChannelFuture channelFuture = null;
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) //非阻塞模式
.handler(new LoggingHandler(LogLevel.DEBUG))
.option(ChannelOption.SO_REUSEADDR, true)
.option(ChannelOption.SO_KEEPALIVE, keepAlive)
.option(ChannelOption.SO_BACKLOG, backlog)
.childHandler(new WSServerInitialzer(nettyHandlerService));
channelFuture = b.bind(new InetSocketAddress(tcpPort)).syncUninterruptibly();
channel = channelFuture.channel();
} catch (Exception e) {
log.error("netty start error {} {}", e.getMessage(), e);
} finally {
if (null != channelFuture && channelFuture.isSuccess()) {
log.info("tCPServerTwo start ok");
} else {
log.error("tCPServerTwo start error ");
}
}
return channelFuture;
}
public void start(Consumer<TtyConnection> handler, final Consumer<Throwable> doneHandler) {
group = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new TtyServerInitializer(channelGroup, handler, workerGroup));
final ChannelFuture f = b.bind(host, port);
f.addListener(new GenericFutureListener<Future<? super Void>>() {
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
if (future.isSuccess()) {
channel = f.channel();
doneHandler.accept(null);
} else {
doneHandler.accept(future.cause());
}
}
});
}
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
} else {
sslCtx = null;
}
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 FactorialServerInitializer(sslCtx));
b.bind(PORT).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
.build();
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();
}
}
public static void main(String[] args) throws Exception {
System.err.println("Proxying *:" + LOCAL_PORT + " to " + REMOTE_HOST + ':' + REMOTE_PORT + " ...");
// Configure the bootstrap.
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 HexDumpProxyInitializer(REMOTE_HOST, REMOTE_PORT))
.childOption(ChannelOption.AUTO_READ, false)
.bind(LOCAL_PORT).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
} else {
sslCtx = null;
}
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 HttpCorsServerInitializer(sslCtx));
b.bind(PORT).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
} else {
sslCtx = null;
}
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 HttpCorsServerInitializer(sslCtx));
b.bind(PORT).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
@Override
protected void initChannel(SocketChannel socketChannel) {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline
// log
.addLast("logging", new LoggingHandler(LogLevel.INFO))
// 心跳检测
// .addLast(new IdleStateHandler(10, 0, 0, TimeUnit.SECONDS))
// .addLast(new HeartBeatHandler())
// 链路管理
.addLast(new ChannelManagerHandler())
;
// 拓展
extHandler(socketChannel.pipeline());
pipeline.addLast(new MqHandler())
// 异常管理
.addLast(new ExceptionHandler())
;
}
public void run() throws Exception {
final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous");
final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
connectFactory, NioUdtProvider.BYTE_PROVIDER);
try {
final Bootstrap bootstrap = new Bootstrap();
bootstrap.group(connectGroup)
.channelFactory(NioUdtProvider.BYTE_RENDEZVOUS)
.handler(new ChannelInitializer<UdtChannel>() {
@Override
protected void initChannel(UdtChannel ch) throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.INFO),
new ByteEchoPeerHandler(messageSize));
}
});
final ChannelFuture future = bootstrap.connect(peerAddress, myAddress).sync();
future.channel().closeFuture().sync();
} finally {
connectGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
} else {
sslCtx = null;
}
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 WorldClockServerInitializer(sslCtx));
b.bind(PORT).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
} else {
sslCtx = null;
}
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 TelnetServerInitializer(sslCtx));
b.bind(PORT).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workGroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringEncoder());
pipeline.addLast(new StringDecoder());
pipeline.addLast(new ServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress("172.28.86.151",8080)).sync();
channelFuture.channel().closeFuture().sync();
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
public static void main(String[] args) throws InterruptedException {
EventLoopGroup workGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY,true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LoggingHandler());
pipeline.addLast(new ClientHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect("172.28.86.151", 8080).sync();
channelFuture.channel().closeFuture().sync();
workGroup.shutdownGracefully();
}
void run() throws Exception {
// Configure the server.
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.option(ChannelOption.SO_BACKLOG, 1024);
b.group(group)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new Http2ServerInitializer());
Channel ch = b.bind(port).sync().channel();
ch.closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
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 ServerInitializer());
ChannelFuture f = b.bind(8888);
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
@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 Server");
//创建boss线程组 用于服务端接受客户端的连接
bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
// 创建 worker 线程组 用于进行 SocketChannel 的数据读写
workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
// 创建 ServerBootstrap 对象
ServerBootstrap b = new ServerBootstrap();
//设置使用的EventLoopGroup
b.group(bossGroup, workerGroup)
//设置要被实例化的为 NioServerSocketChannel 类
.channel(NioServerSocketChannel.class)
// 设置 NioServerSocketChannel 的处理器
.handler(new LoggingHandler(LogLevel.INFO))
// 设置连入服务端的 Client 的 SocketChannel 的处理器
.childHandler(new NettyServerInitializer());
// 绑定端口,并同步等待成功,即启动服务端
channelFuture = b.bind(port).sync();
log.info("Server started!");
}
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.option(ChannelOption.SO_BACKLOG, 1024);
b.childOption(ChannelOption.TCP_NODELAY,true);
b.childOption(ChannelOption.SO_KEEPALIVE,true);
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new HttpHelloWorldServerInitializer());
Channel ch = b.bind(PORT).sync().channel();
logger.info("Netty http server listening on port "+ PORT);
ch.closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public void start(Consumer<TtyConnection> handler, final Consumer<Throwable> doneHandler) {
group = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new TtyServerInitializer(channelGroup, handler, httpResourcePath));
final ChannelFuture f = b.bind(host, port);
f.addListener(new GenericFutureListener<Future<? super Void>>() {
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
if (future.isSuccess()) {
channel = f.channel();
doneHandler.accept(null);
} else {
doneHandler.accept(future.cause());
}
}
});
}
public NettyIoAcceptor(NettyIoServiceFactory factory, final IoHandler handler) {
this.factory = factory;
this.handler = handler;
channelGroup = new DefaultChannelGroup("sshd-acceptor-channels", GlobalEventExecutor.INSTANCE);
bootstrap.group(factory.eventLoopGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new NettyIoSession(NettyIoAcceptor.this, handler).adapter);
}
});
}
public static void main(String[] args) throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslCtx = SslContextGMBuilder.forServer(ENC_CERT, ENC_KEY, SIGN_CERT, SIGN_KEY, null)
/* 默认协商出来的是ECDHE_SM4_SM3算法,所以必须是双向SSL,并且客户端和服务端必须要有加密证书和签名证书 */
.clientAuth(ClientAuth.REQUIRE)
.build();
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();
}
}
public static HttpAgent initialize(
final HttpRequestChannelConsumerProvider provider,
final int port,
final boolean useSSL,
final int numberOfThreads,
final Logger logger)
throws Exception {
final SslContext sslContext = useSSL ? sslContext() : null;
final OptimalTransport optimalTransport = optimalTransport(logger);
final EventLoopGroup bossGroup = eventLoopGroup(optimalTransport, numberOfThreads, logger);
final EventLoopGroup workerGroup = eventLoopGroup(optimalTransport, logger);
ServerBootstrap bootstrap =
new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(serverSocketChannelType(optimalTransport, logger))
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new AgentInitializer(provider, sslContext, logger));
return new HttpAgent(bootstrap.bind(port).sync().channel(), bossGroup, workerGroup);
}
public void start() throws InterruptedException {
//为启动引导器
ServerBootstrap bootstrap = new ServerBootstrap();
//时间循环器,两个组实际上是两个线程组
//bossGroup 负责获取客户端连接,接收到之后会将该连接转发到 workerGroup 进行处理
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup work = new NioEventLoopGroup();
try {
bootstrap.group(boss, work)
.option(ChannelOption.SO_BACKLOG, 1024)
.handler(new LoggingHandler(LogLevel.INFO))
.channel(NioServerSocketChannel.class)
.childHandler(new HttpServerInitializer());
Channel ch = bootstrap.bind(port).sync().channel();
System.out.println("Netty http server listening on port " + port);
ch.closeFuture().sync();
} finally {
boss.shutdownGracefully();
work.shutdownGracefully();
}
}
public void start() throws Exception{
if (!PortChecker.checkPort(null, port)) {
throw new Exception("请确保所需要内部管理端口" + port + "没有被占用");
}
InetSocketAddress addr = new InetSocketAddress(ip,port);
// 启动ip和端口
final String adInfo = ip + ":" + port;
startThread = new Thread(){
@Override
public void run(){
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,wokerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new HttpNettyServerInitializer());
ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(port)).sync();
logger.info("HTTP service start success ---"+adInfo);
future.channel().closeFuture().sync();
}catch (Exception e){
logger.error("HTTP Service start fail ---"+adInfo+e.getMessage());
}finally {
bossGroup.shutdownGracefully();
wokerGroup.shutdownGracefully();
}
}
};
startThread.start();
}
private void handleNettyInit(){
mBootstrap = new Bootstrap();
mBootstrap.channel(NioSocketChannel.class);
mGroup = new NioEventLoopGroup();
mBootstrap.group(mGroup)
.option(ChannelOption.TCP_NODELAY, true)// 消息立即发出去
.option(ChannelOption.SO_REUSEADDR, true)
.handler(new LoggingHandler(isDebug ? LogLevel.DEBUG : LogLevel.INFO));
mBootstrap.handler(mChannelInitializer);
}