Netty之入门案例,linux教程第四版答案第五章

这篇博客介绍了Netty的基本用法,通过创建一个简单的定时器服务端和客户端来展示其工作原理。服务器使用NioEventLoopGroup处理连接,并配置了自定义的TimerServerHandler来读取和响应客户端请求。客户端同样使用NioEventLoopGroup发起连接,并配置了TimeClientHandler进行通信。文章还提及了log4j的日志配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

log4j.rootCategory=info, stdout , R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n

log4j.appender.R=org.apache.log4j.DailyRollingFileAppender

log4j.appender.R.File=C:\Tomcat 5.5\logs\qc.log

log4j.appender.R.layout=org.apache.log4j.PatternLayout

log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

服务端


TimerServer

package com.dpb.netty.demo;

import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.ChannelOption;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TimerServer {

public void bind(int port) throws Exception{

// 配置服务端的NIO线程组

// 服务端接受客户端的连接

NioEventLoopGroup bossGroup = new NioEventLoopGroup();

// 进行SocketChannel的网络读写

NioEventLoopGroup workerGroup = new NioEventLoopGroup();

try {

// 用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度

ServerBootstrap b = new ServerBootstrap();

b.group(bossGroup,workerGroup)

// 设置Channel

.channel(NioServerSocketChannel.class)

// 设置TCP参数

.option(ChannelOption.SO_BACKLOG, 1024)

// 绑定I/O事件的处理类ChildChannelHandler

.childHandler(new ChildChannelHandler());

// 绑定端口,同步等待成功

ChannelFuture f = b.bind(port).sync();

// 等待服务端监听端口关闭

f.channel().closeFuture().sync();

} finally {

// 优雅退出,释放线程池资源

bossGroup.shutdownGracefully();

workerGroup.shutdownGracefully();

}

}

private class ChildChannelHandler extends ChannelInitializer{

@Override

protected void initChannel(SocketChannel arg0) throws Exception {

arg0.pipeline().addLast(new TimerServerHandler());

}

}

public static void main(String[] args) throws Exception {

int port = 8080;

new TimerServer().bind(port);

}

}

TimerServerHandler

package com.dpb.netty.demo;

import java.nio.ByteBuffer;

import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

/**

  • 用于对网络事件进行读写操作

  • @author 波波烤鸭

  • @email dengpbs@163.com

*/

public class TimerServerHandler extends ChannelHandlerAdapter{

@Override

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

// ByteBuf 类似于NIO中的java.nio.ByteBuffer对象,

ByteBuf buf = (ByteBuf) msg;

byte[] req = new byte[buf.readableBytes()];

buf.readBytes(req);

String body = new String(req,“utf-8”);

System.out.println("The time server receive order : "+body);

String currentTime = “Query time order”.equalsIgnoreCase(body)?new java.util.Date(System.currentTimeMillis()).toString():“BAD ORDER”;

ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());

ctx.write(resp);

}

@Override

public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

// TODO Auto-generated method stub

ctx.flush();

}

@Override

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

// TODO Auto-generated method stub

ctx.close();

}

}

客户端


TimeClient

package com.dpb.netty.demo;

import io.netty.bootstrap.Bootstrap;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.ChannelOption;

import io.netty.channel.EventLoopGroup;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioSocketChannel;

public class TimeClient {

public static void main(String[] args) throws Exception {

int port = 8080;

new TimeClient().connect(port, “127.0.0.1”);

}

public void connect(int port,String host)throws Exception{

// 配置客户端NIO线程组

EventLoopGroup group = new NioEventLoopGroup();

try{

Bootstrap b = new Bootstrap();

b.group(group).channel(NioSocketChannel.class)

.option(ChannelOption.TCP_NODELAY, true)

.handler(new ChannelInitializer() {

@Override

protected void initChannel(SocketChannel arg0) throws Exception {

arg0.pipeline().addLast(new TimeClientHandler());

}

});

// 发起异步连接操作

ChannelFuture f = b.connect(host,port).sync();

// 等待客户端链路关闭

f.channel().closeFuture().sync();

}catch(Exception e){

e.printStackTrace();

}finally{

// 优雅退出,释放NIO线程组

group.shutdownGracefully();

}

}

}

TimeClientHandler

package com.dpb.netty.demo;

import java.util.logging.Logger;

import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

public class TimeClientHandler extends ChannelHandlerAdapter{

private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值