服务器端:
import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
//1、创建两个线程组 bossGroup workGroup
//bossGroup线程组负责客户端连接
EventLoopGroup bossGroup=new NioEventLoopGroup();
//workGroup线程组负责网络读写操作
EventLoopGroup workGroup=new NioEventLoopGroup();
//2、创建服务器启动助手来配置参数--创建辅助的工具类,用于服务器通道的一些列配置
ServerBootstrap serverBootstrap=new ServerBootstrap();
//链式编程
serverBootstrap.group(bossGroup,workGroup)//绑定两个线程组
.channel(NioServerSocketChannel.class)//指定NIO模式
.option(ChannelOption.SO_BACKLOG,512)//设置TCP缓冲区
.childOption(ChannelOption.SO_KEEPALIVE,true)//保持连接
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {//数据 接收方法的处理
ch.pipeline().addLast(new NettyServerHandler());//具体业务的处理
}
});
System.out.println("Server : 准备就绪!!!");
//3 绑定端口,设置非堵塞,,这里是一个异步操作
ChannelFuture cf = serverBootstrap.bind(8765).sync();
ChannelFuture cf2 = serverBootstrap.bind(8766).sync();//--绑定多个端口,开口变大,但是处理能力不变
System.out.println("Server : 启动!!!");
//4 关闭通道
cf.channel().closeFuture().sync();//等待关闭
cf2.channel().closeFuture().sync();//等待关闭
System.out.println("Server--关闭通道!!!");
//关闭线程组
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
System.out.println("Server--关闭线程组!!!");
}
}
服务器业务处理类:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import javax.sound.midi.Soundbank;
//普通类变成业务处理类需要继承一个类或者实现一个接口
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
//数据的读取事件
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws
Exception {
System.out.println("serverHandler--ctx:"+ctx);
ByteBuf buffer= (ByteBuf) msg;
System.out.println("来自客户端的消息:"+buffer.toString(CharsetUtil.UTF_8));
}
//数据读取完毕事件
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
{
ChannelFuture channelFuture =
ctx.writeAndFlush(Unpooled.copiedBuffer("hi,client,我收到你的消息啦!", CharsetUtil.UTF_8));
//添加监听事件:数据发送完毕之后,直接断开客户端的连接
// channelFuture.addListener(ChannelFutureListener.CLOSE);
}
//异常捕捉事件
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
ctx.close();
}
}
客户端:
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 NettyClient {
public void run() throws InterruptedException {
EventLoopGroup group=new NioEventLoopGroup();
//创建客户端的启动助手
Bootstrap bootstrap=new Bootstrap();
//开始配置
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws
Exception {
ch.pipeline().addLast(new NettyClientHandler());//具体业务处理
}
});
System.out.println("Client: 准备就绪!!!");
//启动客户端去连接服务器
ChannelFuture cf = bootstrap.connect("127.0.0.1", 8765).sync();
ChannelFuture cf2 = bootstrap.connect("127.0.0.1", 8766).sync();
//服务器端断开连接这边才会断开连接的,
cf.channel().closeFuture().sync();//等待关闭
cf2.channel().closeFuture().sync();//等待关闭
System.out.println("Client--关闭通道!!!");
group.shutdownGracefully();
System.out.println("Client--关闭线程组!!!");
}
public static void main(String[] args) {
try {
new NettyClient().run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
客户端业务处理类:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
//客户端业务处理类
//入站操作,进入pipeline里面
public class NettyClientHandler extends ChannelInboundHandlerAdapter{
//通道就绪
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Client: ctx="+ctx);
ctx.writeAndFlush(Unpooled.copiedBuffer("hi,server,这是来自客户端的招呼!", CharsetUtil.UTF_8));
}
//数据的读取事件
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws
Exception {
ByteBuf buf = (ByteBuf) msg;
System.out.println("服务器回复的消息:" + buf.toString(CharsetUtil.UTF_8));
}
}
当服务器断开以后,客户端会执行断开连接的操作。