System.out.println("服务端停止服务!!!");
}
}
1)、在这里将业逻辑注入,这样就很好的将业务和IO操作分离开了
**通道初始化类:ServerChannelInit.java**
public class ServerChannelInit extends ChannelInitializer { @Override protected void initChannel(NioSocketChannel ch) throws Exception { //对服务端管道进行配置,编解码,Handler的处理顺序等等 ch.pipeline() .addLast(new StringEncoder()) .addLast(new StringDecoder()) .addLast(new ServerHandler()); } }
**通道数据处理类:ServerHandler.java**
public class ServerHandler extends SimpleChannelInboundHandler {
@Override
public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("接受到数据是:"+msg);
//返回响应
ctx.writeAndFlush("服务端已经接受数据!!");
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("=============test通道激活============");
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("=============test通道激活ing============");
super.channelInactive(ctx);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("=============test通道数据读取完毕!!============");
super.channelReadComplete(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("=============test通道激活出现异常============");
super.exceptionCaught(ctx, cause);
ctx.close();
}
}
### 客户端实现
**启动类:Client.java**
public class Client { public static void main(String[] args) throws Exception{ NioEventLoopGroup workGroup = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); ChannelFuture cf = b.group(workGroup) .channel(NioSocketChannel.class) .handler(new ClientChannelInit()) .connect("127.0.0.1", 8899) .sync(); server",CharsetUtil.UTF_8)); System.out.println("客户端初始化完成!!!!"); cf.channel().closeFuture().sync(); } }
**通道初始化类:ClientChannelInit.java**
public class ClientChannelInit extends ChannelInitializer { @Override protected void initChannel(NioSocketChannel ch) throws Exception { ch.pipeline() .addLast(new StringEncoder()) .addLast(new StringDecoder()) .addLast(new ClientHandler()); } }
**通道数据处理类:ClientHandler.java**
public class ClientHandler extends SimpleChannelInboundHandler { @Override public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("接受到服务端的消息:"+msg); }
/\*\*
* 在channel初始化的时候,发送数据 * @param ctx * @throws Exception */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush("hello server"); } }
### 总结


**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
**[需要这份系统化的资料的朋友,可以添加戳这里获取](https://gitee.com/vip204888)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**