一、服务端代码模板
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
//server启动器
ServerBootstrap serverBootstrap = new ServerBootstrap();
//boss线程组,监听端口链接
NioEventLoopGroup boss = new NioEventLoopGroup(1);
//worker线程组,监听数据读写
NioEventLoopGroup worker = new NioEventLoopGroup();
try {
serverBootstrap
//1.指定线程组
.group(boss, worker)
//2.指定线程模型
.channel(NioServerSocketChannel.class)
//3.初始化pipeline
.childHandler(new ChannelInitializer<NioSocketChannel>() {
protected void initChannel(NioSocketChannel ch) {
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
System.out.println(msg);
}
});
}
});
//5.绑定端口并阻塞至完成
ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
//6.阻塞当前线程至ServerSocketChannel关闭(根据情况判断是否阻塞当前线程,也可以添加监听器进行关闭)
channelFuture.channel().closeFuture().sync();
}finally {
//7.优雅关闭
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
二、客户端代码模板
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
//启动器
Bootstrap bootstrap = new Bootstrap();
//线程组,客户端不需要监听端口,只需要一个线程组
NioEventLoopGroup group = new NioEventLoopGroup();
try {
bootstrap
//1.指定线程组
.group(group)
//2.指定线程模型
.channel(NioSocketChannel.class)
//3.初始化pipeline
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new StringEncoder());
}
});
//4.链接服务端
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8888).sync();
//5.获取channel(一般都单独保存,用于通信)
Channel channel = channelFuture.channel();
//6.阻塞当前线程至SocketChannel关闭(根据情况判断是否阻塞当前线程,也可以添加监听器进行关闭,客户端一般都不需要阻塞)
channel.closeFuture().sync();
} finally {
//7.优雅关闭
group.shutdownGracefully();
}
}
}
还没有评论,来说两句吧...