入门案例
1、博主使用的IDE是idea,很强大的开发工具 2、为了精简篇幅,博主把代码中需要导入包那一块去除了,大家在操作的时候需要手动导包 3、入门案例的每一行代码都有对应的注释,便于大家理解
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.15.Final</version>
</dependency>
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
// 创建线程池 接受连接
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
// 创建线程池,处理io
NioEventLoopGroup workGroup = new NioEventLoopGroup();
// 创建服务器端启动助手
ServerBootstrap serverBootstrap = new ServerBootstrap();
// 配置启动助手
serverBootstrap.group(bossGroup, workGroup)//设置两个线程池
.channel(NioServerSocketChannel.class)//使用作为服务器端的通道实现
.option(ChannelOption.SO_BACKLOG, 128)//设置线程队列中等待连接的个数
.childOption(ChannelOption.SO_KEEPALIVE, true)//保持活动连接状态
.childHandler(new ChannelInitializer<SocketChannel>() { //创建通道初始化的对象
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new NettyServerHandler());
}
});
System.out.println("----------------server is ready--------------------");
ChannelFuture cf = serverBootstrap.bind(9999).sync();//绑定端口,异步
System.out.println("----------------server is starting--------------------");
// 关闭通道、关闭通道组
cf.channel().closeFuture().sync();
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
/**
* 服务器业务处理块
*/
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
/**
* 读取数据事件
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("server:"+ctx);
ByteBuf buf = (ByteBuf)msg;
System.out.println("客户端发来消息:"+buf.toString(CharsetUtil.UTF_8));
}
/**
*数据读取完毕
* @param ctx
* @throws Exception
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.copiedBuffer("就是没钱啦!",CharsetUtil.UTF_8));
}
/**
* 异常发生
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
// 创建一个线程组
NioEventLoopGroup group = new NioEventLoopGroup();
//2. 创建客户端的启动助手,完成相关配置
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)//3. 设置线程组
.channel(NioSocketChannel.class)//4. 设置客户端通道的实现类
.handler(new ChannelInitializer<SocketChannel>() {//5. 创建一个通道初始化对象
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new NettyClientHandler());//6.往Pipeline链中添加自定义的handler
}
});
System.out.println("......Client is ready......");
//7.启动客户端去连接服务器端 connect方法是异步的 sync方法是同步阻塞的
ChannelFuture cf = bootstrap.connect("127.0.0.1", 9999).sync();
// 关闭连接
cf.channel().closeFuture().sync();
}
}
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
/**
* 通道就绪事件
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client:"+ctx);
ctx.writeAndFlush(Unpooled.copiedBuffer("老板还钱吧!", CharsetUtil.UTF_8));
}
/**
* 读取数据
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf)msg;
System.out.println("服务器发来消息:"+buf.toString(CharsetUtil.UTF_8));
}
}
服务器端 ----------------server is ready-------------------- ----------------server is starting-------------------- server:ChannelHandlerContext(NettyServerHandler#0, [id: 0xa80ee519, L:/127.0.0.1:9999 - R:/127.0.0.1:60798]) 客户端发来消息:老板还钱吧! 客户端: ......Client is ready...... client:ChannelHandlerContext(NettyClientHandler#0, [id: 0xe77a3b4a, L:/127.0.0.1:60798 - R:/127.0.0.1:9999]) 服务器发来消息:就是没钱啦!