Netty 是一个基于NIO的客户、服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户,服务端应用。Netty相当简化和流线化了网络应用的编程开发过程,例如,TCP和UDP的socket服务开发。

  Netty简单来说就是socket通讯,支持多协议的通讯

对 创建 netty 的过程作了详细的解析

1、简单创建一个Netty服务器

  1. package com.netty.test;
  2.  
  3. import java.net.InetAddress;
  4.  
  5. import io.netty.bootstrap.ServerBootstrap;
  6. import io.netty.channel.ChannelFuture;
  7. import io.netty.channel.ChannelHandlerContext;
  8. import io.netty.channel.ChannelInboundHandlerAdapter;
  9. import io.netty.channel.ChannelInitializer;
  10. import io.netty.channel.ChannelOption;
  11. import io.netty.channel.EventLoopGroup;
  12. import io.netty.channel.nio.NioEventLoopGroup;
  13. import io.netty.channel.socket.SocketChannel;
  14. import io.netty.channel.socket.nio.NioServerSocketChannel;
  15. import io.netty.handler.codec.DelimiterBasedFrameDecoder;
  16. import io.netty.handler.codec.Delimiters;
  17. import io.netty.handler.codec.string.StringDecoder;
  18. import io.netty.handler.codec.string.StringEncoder;
  19.  
  20. /**
  21. * Netty4 服务端代码
  22. *
  23. */
  24. public class HelloWorldServer {
  25.  
  26. public static void main(String[] args) {
  27. // EventLoop 代替原来的 ChannelFactory
  28. EventLoopGroup bossGroup = new NioEventLoopGroup();
  29. EventLoopGroup workerGroup = new NioEventLoopGroup();
  30.  
  31. try {
  32. ServerBootstrap serverBootstrap = new ServerBootstrap();        //创建 一个netty 服务器
  33. // server端采用简洁的连写方式,client端才用分段普通写法。
  34. serverBootstrap.group(bossGroup, workerGroup)
  35. .channel(NioServerSocketChannel.class)              // 指定channel[通道]类型
  36. .childHandler(new ChannelInitializer<SocketChannel>() {    // 指定Handler [操纵者]
  37. @Override
  38. public void initChannel(SocketChannel ch) throws Exception {
  39. // 以("\n")为结尾分割的 解码器
  40. ch.pipeline().addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
  41.  
  42. // 字符串 解码 和 编码 默认的 StringDecoder 字符串形式输出
  43. ch.pipeline().addLast("decoder", new StringDecoder());
  44. ch.pipeline().addLast("encoder", new StringEncoder());
  45.  
  46. ch.pipeline().addLast(new HelloServerHandler());     // 添加自己的对 上传数据的处理
  47. }
  48. }).option(ChannelOption.SO_KEEPALIVE, true);
  49.        ChannelFuture f = serverBootstrap.bind(8000).sync();           // 绑定 8000 端口
  50. f.channel().closeFuture().sync();
  51.  
  52. }
  53. catch (InterruptedException e) {
  54.  
  55. } finally {
  56. workerGroup.shutdownGracefully(); // 销毁 netty
  57. bossGroup.shutdownGracefully();
  58. }
  59. }
  60.  
  61. /**
  62. * 自己对 处理数据
  63. *
  64. * @author flm
  65. * 2017年11月10日
  66. */
  67. private static class HelloServerHandler extends ChannelInboundHandlerAdapter {
  68.  
  69. @Override
  70. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  71. // 收到消息直接打印输出
  72. System.out.println(ctx.channel().remoteAddress() + " Say : " + msg);
  73.  
  74. // 返回客户端消息 - 我已经接收到了你的消息
  75. ctx.writeAndFlush("server Received your message !\n");
  76. }
  77.  
  78. /*
  79. *
  80. * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)
  81. *
  82. * channelActive 和 channelInActive 在后面的内容中讲述,这里先不做详细的描述
  83. */
  84. @Override
  85. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  86.  
  87. System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");
  88.  
  89. ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n"); //回复
  90.  
  91. super.channelActive(ctx);
  92. }
  93. }

2、netty 客户端 创建

  1. package com.netty.test;
  2.  
  3. import java.net.InetSocketAddress;
  4. import java.util.Date;
  5.  
  6. import io.netty.bootstrap.Bootstrap;
  7. import io.netty.channel.Channel;
  8. import io.netty.channel.ChannelHandlerContext;
  9. import io.netty.channel.ChannelInboundHandlerAdapter;
  10. import io.netty.channel.ChannelInitializer;
  11. import io.netty.channel.ChannelPipeline;
  12. import io.netty.channel.nio.NioEventLoopGroup;
  13. import io.netty.channel.socket.nio.NioSocketChannel;
  14. import io.netty.handler.codec.DelimiterBasedFrameDecoder;
  15. import io.netty.handler.codec.Delimiters;
  16. import io.netty.handler.codec.string.StringDecoder;
  17. import io.netty.handler.codec.string.StringEncoder;
  18.  
  19. /**
  20. * Netty4 客户端代码
  21. *
  22. */
  23. public class HelloWorldClient {
  24.  
  25. public static void main(String args[]) {
  26.  
  27. // Bootstrap,且构造函数变化很大,这里用无参构造。
  28. Bootstrap bootstrap = new Bootstrap();
  29. // 指定channel[通道]类型
  30. bootstrap.channel(NioSocketChannel.class);
  31. // 指定Handler [操纵者]
  32. bootstrap.handler(new ChannelInitializer<Channel>() {
  33.  
  34. @Override
  35. protected void initChannel(Channel ch) throws Exception {
  36. ChannelPipeline pipeline = ch.pipeline();
  37.  
  38. /*
  39. * 这个地方的 必须和服务端对应上。否则无法正常解码和编码
  40. *
  41. */
  42. pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
  43. pipeline.addLast("decoder", new StringDecoder());
  44. pipeline.addLast("encoder", new StringEncoder());
  45.  
  46. // 客户端的逻辑,自己对数据处理
  47. pipeline.addLast(new HelloClientHandler());
  48. }
  49. });
  50. // 指定EventLoopGroup [事件 组]
  51. bootstrap.group(new NioEventLoopGroup());
  52.  
  53. // 连接到本地的8000端口的服务端
  54. bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000));
  55.  
  56. }
  57.  
  58. /**
  59. * 客户端的逻辑,自己对数据处理
  60. *
  61. * @author flm
  62. * 2017年11月10日
  63. */
  64. private static class HelloClientHandler extends ChannelInboundHandlerAdapter {
  65.  
  66. /*
  67. * 监听 服务器 发送来的数据
  68. */
  69. @Override
  70. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  71.  
  72. System.out.println("Server say : " + msg.toString());
  73.  
  74. }
  75.  
  76. /*
  77. * 启动客户端 时触发
  78. */
  79. @Override
  80. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  81. System.out.println("Client active ");
  82. ctx.writeAndFlush("我是 client " + new Date() + "\n");
  83. super.channelActive(ctx);
  84. }
  85.  
  86. /*
  87. * 关闭 客户端 触发
  88. */
  89. @Override
  90. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  91. System.out.println("Client close ");
  92. super.channelInactive(ctx);
  93. }
  94. }
  95. }

Netty——简单创建服务器、客户端通讯的更多相关文章

  1. 运用socket实现简单的服务器客户端交互

    Socket解释: 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket. Socket的英文原义是“孔”或“插座”.作为BSD UNIX的进程通信机制,取后一种意 ...

  2. 【Netty】Netty简介及服务器客户端简单开发流程

    什么是Netty Netty是一个基于Java NIO的编写客服端服务器的框架,是一个异步事件框架. 官网https://netty.io/ 为什么选择Netty 由于JAVA NIO编写服务器的过程 ...

  3. 【Echo】实验 -- 实现 C/C++下TCP, 服务器/客户端 通讯

    本次实验利用TCP/IP, 语言环境为 C/C++ 利用套接字Socket编程,实现Server/CLient 之间简单的通讯. 结果应为类似所示: 下面贴上代码(参考参考...) Server 部分 ...

  4. 【Echo】实验 -- 实现 C/C++下UDP, 服务器/客户端 通讯

    本次实验利用UDP协议, 语言环境为 C/C++ 利用套接字Socket编程,实现Server/CLient 之间简单的通讯. 结果应为类似所示: 下面贴上代码(参考参考...) Server 部分: ...

  5. Windows Socket 编程_ 简单的服务器/客户端程序

    转载自:http://blog.csdn.net/neicole/article/details/7459021 一.程序运行效果图 二.程序源代码 三.程序设计相关基础知识 1.计算机网络    2 ...

  6. 简单实现服务器/客户端的c代码

    #include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> ...

  7. Java新AIO/NIO2:AsynchronousServerSocketChannel和AsynchronousSocketChannel简单服务器-客户端

    Java新AIO/NIO2:AsynchronousServerSocketChannel和AsynchronousSocketChannel简单服务器-客户端用AsynchronousServerS ...

  8. Netty创建服务器与客户端

    Netty 创建Server服务端 Netty创建全部都是实现自AbstractBootstrap.客户端的是Bootstrap,服务端的则是ServerBootstrap. 创建一个 HelloSe ...

  9. macos下简单的socket服务器+客户端

    TCP客户端服务器编程模型: 服务器: 调用socket函数创建套接字 调用bind绑定本地IP和端口 调用listen启动监听(准备好接收客户端链接的队列) 调用accept从已连接队列中提取第一个 ...

随机推荐

  1. HDU 5976 数学

    Detachment Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total ...

  2. S2_SQL_第三章

    3.1:修改表 3.1.1:修改表 语法: Alter table <旧表名> rename [ TO] <新表名>; 例子:Alter table `demo01` rena ...

  3. Node.js学习之TCP/IP数据通讯

    Node.js学习之TCP/IP数据通讯 1.使用net模块实现基于TCP的数据通讯 提供了一个net模块,专用于实现TCP服务器与TCP客户端之间的通信 1.1创建TCP服务器 在Node.js利用 ...

  4. C-图文上边对齐

    1.效果 1.1 样式设置 2 效果  2.1 样式

  5. Ubuntu 14.04 安装 Sublime Text 3

    1. 实验环境 Ubuntu 14.04 + Sublime text 3 2. sublime text介绍 ublime Text 是一款流行的文本编辑器软件,有点类似于TextMate,跨平台, ...

  6. 关于java的自动拆装箱若干细节问题

    一.首先需要了解的几个前提: 1.自动装箱过程是通过调用valueOf方法实现的(如Integer.valueOf(10)),而拆箱过程是通过调用包装器的 xxxValue方法实现的(如Integer ...

  7. Charle抓包与wireshark使用

    今天就来看一下Mac上如何进行抓包,之前有一篇文章介绍了使用Fidder进行抓包 http://blog.csdn.net/jiangwei0910410003/article/details/198 ...

  8. Android 性能优化概念(1)

    http://www.open-open.com/lib/view/open1421723359718.html#_label0 阅读目录 0)Render Performance 1)Underst ...

  9. oracle导不出空表的解决办法

    1.先进行表分析(一定要执行此步,否则查询空表可能不准确) select 'analyze table '||table_name||' compute statistics;' from user_ ...

  10. 【转】深入浅出:Linux设备驱动之字符设备驱动

    深入浅出:Linux设备驱动之字符设备驱动 一.linux系统将设备分为3类:字符设备.块设备.网络设备.使用驱动程序: 字符设备:是指只能一个字节一个字节读写的设备,不能随机读取设备内存中的某一数据 ...