1. package com.example.demohystrix.process;
  2.  
  3. import io.netty.bootstrap.ServerBootstrap;
  4. import io.netty.channel.ChannelFuture;
  5. import io.netty.channel.ChannelInitializer;
  6. import io.netty.channel.ChannelOption;
  7. import io.netty.channel.EventLoopGroup;
  8. import io.netty.channel.nio.NioEventLoopGroup;
  9. import io.netty.channel.socket.SocketChannel;
  10. import io.netty.channel.socket.nio.NioServerSocketChannel;
  11. import io.netty.handler.codec.bytes.ByteArrayEncoder;
  12. import io.netty.handler.codec.string.StringEncoder;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15.  
  16. import java.nio.charset.Charset;
  17.  
  18. /**
  19. * @author liusongwei
  20. * @Title: NettyServer
  21. * @ProjectName claimfront
  22. * @Description: TODO
  23. * @date 2019/3/2216:26
  24. */
  25. public class NettyServer {
  26. private static Logger log = LoggerFactory.getLogger(NettyServer.class);
  27.  
  28. private final int port;
  29.  
  30. public NettyServer(int port) {
  31. this.port = port;
  32. }
  33.  
  34. public void start() throws Exception {
  35. //用来接收进来的连接
  36. EventLoopGroup bossGroup = new NioEventLoopGroup();
  37.  
  38. //用来处理已经被接收的连接
  39. EventLoopGroup group = new NioEventLoopGroup();
  40. try {
  41. //启动 NIO 服务的辅助启动类
  42. ServerBootstrap sb = new ServerBootstrap();
  43. sb.option(ChannelOption.SO_BACKLOG, );//设置TCP缓冲区
  44. // sb.option(ChannelOption.SO_SNDBUF,32*1024);//设置发送缓冲大小
  45. // sb.option(ChannelOption.SO_RCVBUF,32*1024);//设置接收缓冲大小
  46. // sb.option(ChannelOption.SO_KEEPALIVE,true);//保持连接
  47. sb.group(group, bossGroup) // 绑定两个线程组
  48. .channel(NioServerSocketChannel.class) // 指定NIO模式
  49. .localAddress(this.port)// 绑定监听端口
  50. // 绑定客户端连接时候触发操作 添加一个EchoServerHandler到子Channel的ChannelPipeline
  51. //ChannelInitializer 当一个新的连接被接收时,一个新的子Channel将会被创建
  52. .childHandler(new ChannelInitializer<SocketChannel>() {
  53. @Override
  54. protected void initChannel(SocketChannel ch) throws Exception {
  55. log.info("客户端连接,连接的IP:{}",ch.localAddress().getHostName());
  56. ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
  57. //EchoServerHandler被标注为@Shareable,所以我们可以总是使用同样的实例
  58. ch.pipeline().addLast(new NettyServerHandler()); // 客户端触发操作
  59. ch.pipeline().addLast(new ByteArrayEncoder());
  60. }
  61. });
  62. //异步绑定服务器,调用sync()方法阻塞等待直到绑定完成
  63. ChannelFuture cf = sb.bind().sync();
  64.  
  65. //获取Channel的closeFuture,并且阻塞当前线程直到它完成
  66. cf.channel().closeFuture().sync();
  67. log.info(" 启动正在监听:{}",cf.channel().localAddress());
  68. } finally {
  69. group.shutdownGracefully().sync(); // 释放线程池资源
  70. bossGroup.shutdownGracefully().sync();
  71. }
  72. }
  73.  
  74. public static void main(String[] args) throws Exception {
  75.  
  76. new NettyServer().start(); // 启动
  77. }
  78. }
  1. package com.example.demohystrix.process;
  2.  
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.ChannelFutureListener;
  6. import io.netty.channel.ChannelHandlerContext;
  7. import io.netty.channel.ChannelInboundHandlerAdapter;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10.  
  11. import java.io.UnsupportedEncodingException;
  12.  
  13. /**
  14. * @author liusongwei
  15. * @Title: NettyServerHandler
  16. * @ProjectName claimfront
  17. * @Description: TODO
  18. * @date 2019/3/2216:31
  19. */
  20. //标示一个ChannelHandler可以被多个Channel安全地共享
  21. public class NettyServerHandler extends ChannelInboundHandlerAdapter {
  22. private static Logger log = LoggerFactory.getLogger(NettyServerHandler.class);
  23. /*
  24. * channel 通道 action 活跃的 回调调用
  25. * 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
  26. */
  27. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  28. System.out.println(ctx.channel().localAddress().toString() + " 通道已激活!");
  29. }
  30.  
  31. /*
  32. * channelInactive
  33. *
  34. * channel 通道 Inactive 不活跃的
  35. *
  36. * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
  37. *
  38. */
  39. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  40. System.out.println(ctx.channel().localAddress().toString() + " 通道不活跃!");
  41. // 关闭流
  42. }
  43.  
  44. /**
  45. * TODO 此处用来处理收到的数据中含有中文的时 出现乱码的问题
  46. */
  47. private String getMessage(ByteBuf buf) {
  48. byte[] con = new byte[buf.readableBytes()];
  49. buf.readBytes(con);
  50. try {
  51. return new String(con, "UTF-8");
  52. } catch (UnsupportedEncodingException e) {
  53. e.printStackTrace();
  54. return null;
  55. }
  56. }
  57.  
  58. /**
  59. * 功能:读取服务器发送过来的信息
  60. */
  61. @Override
  62. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  63. // 第一种:接收字符串时的处理
  64. ByteBuf buf = (ByteBuf) msg;
  65. String rev = getMessage(buf);
  66. log.info("服务端收到的数据:" + rev);
  67. //将接收到的消息写给发送者,而不冲刷出站消息
  68. ctx.write("消息已接收");
  69. }
  70.  
  71. /**
  72. * 功能:读取完毕客户端发送过来的数据之后的操作
  73. */
  74. @Override
  75. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  76. System.out.println("服务端接收数据完毕..");
  77. // 第一种方法:写一个空的buf,并刷新写出区域。完成后关闭sock channel连接。
  78. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
  79. // ctx.flush();
  80. // ctx.flush(); //
  81. // 第二种方法:在client端关闭channel连接,这样的话,会触发两次channelReadComplete方法。
  82. // ctx.flush().close().sync(); // 第三种:改成这种写法也可以,但是这中写法,没有第一种方法的好。
  83. }
  84.  
  85. /**
  86. * 功能:服务端发生异常的操作
  87. */
  88. @Override
  89. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  90. ctx.close();
  91. System.out.println("异常信息:\r\n" + cause.getMessage());
  92. }
  93. }
  1. package com.example.demohystrix.process;
  2.  
  3. import java.net.InetSocketAddress;
  4. import java.nio.charset.Charset;
  5.  
  6. import io.netty.bootstrap.Bootstrap;
  7. import io.netty.channel.ChannelFuture;
  8. import io.netty.channel.ChannelInitializer;
  9. import io.netty.channel.EventLoopGroup;
  10. import io.netty.channel.nio.NioEventLoopGroup;
  11. import io.netty.channel.socket.SocketChannel;
  12. import io.netty.channel.socket.nio.NioSocketChannel;
  13. import io.netty.handler.codec.bytes.ByteArrayEncoder;
  14. import io.netty.handler.codec.string.StringEncoder;
  15. import io.netty.handler.stream.ChunkedWriteHandler;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18.  
  19. /**
  20. * @author liusongwei
  21. * @Title: NettyClient
  22. * @ProjectName algorithmrsa
  23. * @Description: TODO
  24. * @date 2019/3/2216:37
  25. */
  26. public class NettyClient {
  27. private static Logger log = LoggerFactory.getLogger(NettyServer.class);
  28.  
  29. private final String host;
  30. private final int port;
  31.  
  32. public NettyClient() {
  33. this();
  34. }
  35.  
  36. public NettyClient(int port) {
  37. this("localhost", port);
  38. }
  39.  
  40. public NettyClient(String host, int port) {
  41. this.host = host;
  42. this.port = port;
  43. }
  44.  
  45. public void start() throws Exception {
  46. EventLoopGroup group = new NioEventLoopGroup();
  47. try {
  48. Bootstrap b = new Bootstrap();
  49. b.group(group) // 注册线程池
  50. .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
  51. .remoteAddress(new InetSocketAddress(this.host, this.port)) // 绑定连接端口和host信息
  52. .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
  53. @Override
  54. protected void initChannel(SocketChannel ch) throws Exception {
  55. //ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
  56. ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
  57. ch.pipeline().addLast(new NettyClientHandler());
  58. ch.pipeline().addLast(new ByteArrayEncoder());
  59. ch.pipeline().addLast(new ChunkedWriteHandler());
  60.  
  61. }
  62. });
  63. ChannelFuture cf = b.connect().sync(); // 异步连接服务器
  64. log.info("服务端连接成功...");
  65. cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
  66. log.info("连接已关闭...");
  67. } finally {
  68. group.shutdownGracefully().sync(); // 释放线程池资源
  69. }
  70. }
  71.  
  72. public static void main(String[] args) throws Exception {
  73. new NettyClient("127.0.0.1", ).start(); // 连接127.0.0.1/65535,并启动
  74. // new NettyClient("127.0.0.1", 8888).start(); // 连接127.0.0.1/65535,并启动
  75.  
  76. }
  77. }
  1. package com.example.demohystrix.process;
  2.  
  3. import java.nio.charset.Charset;
  4.  
  5. import io.netty.buffer.ByteBuf;
  6. import io.netty.buffer.ByteBufUtil;
  7. import io.netty.buffer.Unpooled;
  8. import io.netty.channel.ChannelHandlerContext;
  9. import io.netty.channel.SimpleChannelInboundHandler;
  10. import io.netty.util.CharsetUtil;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13.  
  14. /**
  15. * @author liusongwei
  16. * @Title: NettyClientHandler
  17. * @ProjectName algorithmrsa
  18. * @Description: TODO
  19. * @date 2019/3/2216:40
  20. */
  21. public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
  22. private static Logger log = LoggerFactory.getLogger(NettyServer.class);
  23. /**
  24. * 向服务端发送数据
  25. */
  26. @Override
  27. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  28. log.info("客户端与服务端通道-开启:" + ctx.channel().localAddress() + "channelActive");
  29. String sendInfo = "Hello 这里是客户端 你好啊!";
  30. ctx.writeAndFlush(Unpooled.copiedBuffer(sendInfo, CharsetUtil.UTF_8)); // 必须有flush
  31. }
  32.  
  33. /**
  34. * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
  35. */
  36. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  37. log.info("客户端与服务端通道-关闭:" + ctx.channel().localAddress() + "channelInactive");
  38. }
  39.  
  40. @Override
  41. protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
  42. System.out.println("读取客户端通道信息..");
  43. ByteBuf buf = msg.readBytes(msg.readableBytes());
  44. //log.info("收到信息:"+ByteBufUtil.hexDump(buf) + "; 数据包为:" + buf.toString(Charset.forName("utf-8")));
  45. log.info("收到信息:"+ByteBufUtil.hexDump(buf) + "; 数据包为:" + buf.toString(Charset.forName("GBK")));
  46. }
  47.  
  48. @Override
  49. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  50. ctx.close();
  51. log.info("异常退出:" + cause.getMessage());
  52. }
  53. }

netty简单样例的更多相关文章

  1. extern外部方法使用C#简单样例

    外部方法使用C#简单样例 1.添加引用using System.Runtime.InteropServices; 2.声明和实现的连接[DllImport("kernel32", ...

  2. spring事务详解(二)简单样例

    系列目录 spring事务详解(一)初探事务 spring事务详解(二)简单样例 spring事务详解(三)源码详解 spring事务详解(四)测试验证 spring事务详解(五)总结提高 一.引子 ...

  3. velocity简单样例

    velocity简单样例整体实现须要三个步骤,详细例如以下: 1.创建一个Javaproject 2.导入须要的jar包 3.创建须要的文件 ============================= ...

  4. 自己定义隐式转换和显式转换c#简单样例

    自己定义隐式转换和显式转换c#简单样例 (出自朱朱家园http://blog.csdn.net/zhgl7688) 样例:对用户user中,usernamefirst name和last name进行 ...

  5. VC6 鼠标钩子 最简单样例

    Windows系统是建立在事件驱动的机制上的,说穿了就是整个系统都是通过消息的传递来实现的.而钩子是Windows系统中非常重要的系统接口,用它能够截获并处理送给其它应用程序的消息,来完毕普通应用程序 ...

  6. gtk+3.0的环境配置及基于gtk+3.0的python简单样例

    /*********************************************************************  * Author  : Samson  * Date   ...

  7. java 使用tess4j实现OCR的最简单样例

    网上很多教程没有介绍清楚tessdata的位置,以及怎么配置,并且对中文库的描述也存在问题,这里介绍一个最简单的样例. 1.使用maven,直接引入依赖,确保你的工程JDK是1.8以上 <dep ...

  8. 使用SALT-API进入集成开发的简单样例

    测试的时候,可以CURL -K,但真正作集成的时候,却是不可以的. 必须,不可以让TOKEN满天飞吧. 现在进入这个阶段了.写个样例先: import salt import salt.auth im ...

  9. VB.net数据库编程(03):一个SQLserver连接查询的简单样例

    这个样例,因为在ADO.net入门已经专门学了,再次进行复习 一下. 主要掌握连接字串的情况. 过程就是: 1.引用System.Data.SqlClient.而Access中引用 的是System. ...

随机推荐

  1. HDU3440 House Man

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission( ...

  2. HDU4609 3-idiots(生成函数)

    题意 链接 Sol 这个题就很休闲了.. 首先这是个数数题,我们要求的是\(\frac{\sum{[a_i + a_j > a_k]}}{C_n^3}\) 其中\(a\)按从小到大排序, \(i ...

  3. Android 9.0新特性

    1.全面屏支持,Android P加入了对刘海屏的支持,谷歌称之为凹口屏幕(display with a cutout).借助最新的提供的DisplayCutout类,开发者可以找到非功能区域的位置和 ...

  4. OpenCV 4.0.1 找不到R.styleable解决

    OpenCV 4.0.1作为模块导入Android Studio会有找不到R.styleable的问题. 解决方法 1.导入模块前 将 opencv-4.0.1-android-sdk\OpenCV- ...

  5. 现有项目中集成Flutter

    本文列举了项目开发使用Flutter会遇到的问题,以及如何使用Flutter module在现有项目中集成Flutter,并对其原理进行了分析. 最近在做的一个商业项目,完全的使用Flutter编写的 ...

  6. 【Spring源码解读】bean标签中的属性(二)你可能还不够了解的 abstract 属性和 parent 属性

    abstract 属性说明 abstract 在java的语义里是代表抽象的意思,用来说明被修饰的类是抽象类.在Spring中bean标签里的 abstract 的含义其实也差不多,表示当前bean是 ...

  7. 整理一些.net core中的错误代码

    在hosting .net core时,有些错误代码并不容易理解. 作为标记,方便查询,这些错误代码可能不会出现在VS的错误查找工具里,也不会出现在错误代码转字符描述的函数里. COR_E_AMBIG ...

  8. Kotlin 或将取代 Java——《Java 编程思想》作者 Bruce Eckel [转]

    Bruce Eckel 是<Java 编程思想>.<C++编程思想>的作者,同时也是 MindView 公司的总裁,该公司向客户提供软件咨询和培训.他是 C++ 标准委员会拥有 ...

  9. Linux网卡聚合时,其中一个网卡有两种配置的解决方法

    先来看看: ficonfig 其中第一网卡是ssh使用: 第二个网卡是在Linux 最小化安装后IP的配置(手动获取静态IP地址)这个文章中配置过ip是192.168.1.2:在Linux重命名网卡名 ...

  10. [20190213]测试服务端打开那些端口.txt

    [20190213]测试服务端打开那些端口.txt --//前几天测试使用发送信息到/dev/tcp/ip_address/port,测试端口是否打开.写简单写一个脚本验证看看. $ seq 1 65 ...