一个简单的netty的程序,主要是netty的客户端和服务端通信。

大部分说明都写在代码注释中

netty server

TimeServer

  1. import io.netty.bootstrap.ServerBootstrap;
  2. import io.netty.channel.ChannelFuture;
  3. import io.netty.channel.ChannelInitializer;
  4. import io.netty.channel.ChannelOption;
  5. import io.netty.channel.EventLoopGroup;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioServerSocketChannel;
  9.  
  10. public class TimeServer {
  11.  
  12. public void bind(int port) throws Exception {
  13.  
  14. // 配置 服务端的 NIO 线程组
  15. EventLoopGroup bossGroup = new NioEventLoopGroup();
  16. EventLoopGroup workerGroup = new NioEventLoopGroup();
  17.  
  18. try {
  19. ServerBootstrap b = new ServerBootstrap();
  20. b.group(bossGroup, workerGroup)
  21. .channel(NioServerSocketChannel.class)
  22. .option(ChannelOption.SO_BACKLOG, 1024)
  23. .childHandler(new ChildChannelHandler());
  24.  
  25. // 绑定端口,同步等待成功。
  26. ChannelFuture f = b.bind(port).sync();
  27. // 等待服务端监听端口关闭。
  28. f.channel().closeFuture().sync();
  29. } catch (Exception e) {
  30. // 退出,释放线程池资源
  31. bossGroup.shutdownGracefully();
  32. workerGroup.shutdownGracefully();
  33. }
  34. }
  35.  
  36. private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
  37. @Override
  38. protected void initChannel(SocketChannel ch) throws Exception {
  39. ch.pipeline().addLast(new TimeServerHandler());
  40. }
  41. }
  42.  
  43. public static void main(String[] args) throws Exception{
  44. int port = 8080;
  45. if (args != null && args.length > 0) {
  46. try {
  47. port = Integer.valueOf(args[0]);
  48. } catch (NumberFormatException e) {
  49. }
  50. }
  51. new TimeServer().bind(port);
  52. }
  53. }

TimeServerHandler

  1. import io.netty.buffer.ByteBuf;
  2. import io.netty.buffer.Unpooled;
  3. import io.netty.channel.ChannelHandlerAdapter;
  4. import io.netty.channel.ChannelHandlerContext;
  5.  
  6. import java.util.Date;
  7.  
  8. public class TimeServerHandler extends ChannelHandlerAdapter {
  9.  
  10. @Override
  11. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  12. ByteBuf buf = (ByteBuf) msg;
  13. byte[] req = new byte[buf.readableBytes()];
  14. buf.readBytes(req);
  15. String body = new String(req,"UTF-8");
  16. System.out.println("the time server receive order : " + body);
  17. String currentTime = "QUERY TIME ORDER"
  18. .equalsIgnoreCase(body) ? new Date(
  19. System.currentTimeMillis()).toString()
  20. : "BAD ORDER";
  21. ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
  22. ctx.write(resp);
  23. }
  24.  
  25. /**
  26. * 当监听到端口时调用 channelActive 打印 "连接成功!"
  27. * @param ctx
  28. * @throws Exception
  29. */
  30. @Override
  31. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  32. System.out.println("连接成功!");
  33. }
  34.  
  35. @Override
  36. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  37. ctx.flush();
  38. }
  39.  
  40. /**
  41. * 当出现异常时,关闭连接
  42. */
  43. @Override
  44. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  45. System.out.println("出现异常,关闭");
  46. ctx.close();
  47. }
  48. }

netty client

TimeClient

  1. import io.netty.bootstrap.Bootstrap;
  2. import io.netty.channel.ChannelFuture;
  3. import io.netty.channel.ChannelInitializer;
  4. import io.netty.channel.ChannelOption;
  5. import io.netty.channel.EventLoopGroup;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioSocketChannel;
  9.  
  10. public class TimeClient {
  11.  
  12. public void connect(int port, String host) throws Exception {
  13.  
  14. //配置客户端 NIO 线程组
  15. EventLoopGroup group = new NioEventLoopGroup();
  16. try {
  17. Bootstrap b = new Bootstrap();
  18. b.group(group).channel(NioSocketChannel.class)
  19. .option(ChannelOption.TCP_NODELAY, true)
  20. .handler(new ChannelInitializer<SocketChannel>() {
  21. @Override
  22. protected void initChannel(SocketChannel ch) throws Exception {
  23.  
  24. ch.pipeline().addLast(new TimeClientHandler());
  25. }
  26. });
  27. // 发起异步连接操作
  28. ChannelFuture f = b.connect(host, port).sync();
  29. // 等待客户端链路关闭
  30. f.channel().closeFuture().sync();
  31. } finally {
  32. // 释放 NIO 线程组
  33. group.shutdownGracefully();
  34.  
  35. }
  36. }
  37.  
  38. public static void main(String[] args) throws Exception {
  39. int port = 8080;
  40.  
  41. if (args != null && args.length > 0) {
  42. try {
  43. port = Integer.valueOf(args[0]);
  44. } catch (NumberFormatException e) {
  45. }
  46. }
  47. new TimeClient().connect(port, "127.0.0.1");
  48. }
  49. }

TimeClientHandler

  1. import io.netty.buffer.ByteBuf;
  2. import io.netty.buffer.Unpooled;
  3. import io.netty.channel.ChannelHandlerAdapter;
  4. import io.netty.channel.ChannelHandlerContext;
  5.  
  6. import java.util.logging.Logger;
  7.  
  8. public class TimeClientHandler extends ChannelHandlerAdapter {
  9.  
  10. private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());
  11.  
  12. private final ByteBuf firstMessage;
  13.  
  14. public TimeClientHandler() {
  15. byte[] req = "QUERY TIME ORDER".getBytes();
  16. firstMessage = Unpooled.buffer(req.length);
  17. firstMessage.writeBytes(req);
  18. }
  19.  
  20. /**
  21. * 当连接成功时,调用 writeAndFlush 发送 firstMessage 到服务端
  22. * @param ctx
  23. * @throws Exception
  24. */
  25. @Override
  26. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  27. ctx.writeAndFlush(firstMessage);
  28. }
  29.  
  30. /**
  31. * 当服务端的有数据发送过来时,调用 channelRead 接受数据,并打印
  32. * @param ctx
  33. * @param msg
  34. * @throws Exception
  35. */
  36. @Override
  37. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  38. ByteBuf buf = (ByteBuf) msg;
  39. byte[] req = new byte[buf.readableBytes()];
  40. buf.readBytes(req);
  41. String body = new String (req,"UTF-8");
  42. System.out.println("Now is : " + body);
  43. }
  44.  
  45. /**
  46. * 出现异常时,打印错误,并关闭
  47. * @param ctx
  48. * @param cause
  49. * @throws Exception
  50. */
  51. @Override
  52. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  53. logger.warning("Unexpected Exception from downstream : " + cause.getMessage());
  54. ctx.close();
  55. }
  56. }

个人感觉netty ,比java自带的NIO简单了很多,不过这只是一个简单小例子,后期可能会有更复杂的 。很期待后边的学习。

第一个简单netty程序的更多相关文章

  1. SpringMVC -- 第一个简单的程序

    学习springMVC,我们来记录下第一个HelloWord的程序 首先.我们组织须要的jar包 commons-logging-1.1.3.jar spring-aop-4.1.7.RELEASE. ...

  2. Netty In Action中国版 - 第二章:第一Netty程序

    本章介绍 获得Netty4最新的版本号 设置执行环境,以构建和执行netty程序 创建一个基于Netty的server和client 拦截和处理异常 编制和执行Nettyserver和client 本 ...

  3. MFC入门(一)-- 第一个简单的windows图形化界面小程序(打开计算器,记事本,查IP)

    ////////////////////////////////序//////////////////////////////// 大约三年前,学过一些简单的编程语言之后其实一直挺苦恼于所写的程序总是 ...

  4. 程序演示:C语言第一个简单实例

    在信息化.智能化的世界里,可能很早很早 我们就听过许多IT类的名词,C语言也在其中,我们侃侃而谈,到底C程序是什么样子?让我们先看简单的一个例子: 1 2 3 4 5 6 7 8 9 #include ...

  5. Netty(1):第一个netty程序

    为什么选择Netty netty是业界最流行的NIO框架之一,它的健壮型,功能,性能,可定制性和可扩展性都是首屈一指的,Hadoop的RPC框架Avro就使用了netty作为底层的通信框架,此外net ...

  6. 图解简单C程序的运行时结构

    程序在内存中的存储分为三个区域,分别是动态数据区.静态数据区和代码区.函数存储在代码区,全局变量以及静态变量存储在静态数据区,而在程序执行的时候才会在动态数据区产生数据.程序执行的本质就是代码区的指令 ...

  7. 编写第一个微信小程序界面

    编写第一个微信小程序界面 不忘初心,方得始终:初心易得,始终难守. 传统的 web 结构 小程序文件目录结构 小程序页面层级结构 编写第一个小程序 1. 创建小程序目录结构 2. 编写代码 welco ...

  8. MFC制作简单通讯录程序

    学习c++和MFC一段时间了,苦于没有项目实战,所以自己写了一个简单的简单通讯录程序,以前用c#写简单很多,例程是这本书上的实例,我的第一个winform程序也是从这本书上学的,总结c#写的话更简单, ...

  9. 创建安全的 Netty 程序

    1.使用 SSL/TLS 创建安全的 Netty 程序 SSL 和 TLS 是众所周知的标准和分层的协议,它们可以确保数据时私有的 Netty提供了SSLHandler对网络数据进行加密 使用Http ...

随机推荐

  1. Android开发 解决Installation failed due to XXX 问题

    报错信息 Android studio 安装app的时候以下报错 Installation did not succeed. The application could not be installe ...

  2. leetcode-241-为运算表达式设置优先级*

    题目描述: 方法:分治* class Solution: def diffWaysToCompute(self, input: str) -> List[int]: if input.isdig ...

  3. Java 虚拟机 - ClassLoader

    ClassLoader定义 ClassLoader种类 BootStrapClassLoader无法在IDEA里面查看源代码,只能看JVM 源码才能找到. ExtClassLoader,会从Syste ...

  4. 把云数据库带回家!阿里云发布POLARDB Box数据库一体机

    9月26日,2019杭州云栖大会上,阿里云宣布正式推出高性能数据库一体机——POLARDB Box,用户部署在自有数据中心即可享受云数据库的便捷体验,同时还为Oracle等传统数据库用户提供一键迁移功 ...

  5. DNS的解析过程

    1.什么是DNS 在互联网上,唯一标识一台计算机的是IP地址,但是IP地址不方便记忆,通过一个域名对应一个IP地址,来达到找到IP地址的目的,那么DNS就是将域名转换成IP地址的过程. 2.DNS查询 ...

  6. python处理多线程之间事件通讯方法

    一.什么是事件 每执行一个事情,肯定有该事情的执行后状态,那事件就是该事情发生的信号 在程序中,多线程之间需要通讯,而事件就是方便线程之间的通讯 案例: 1.服务器启动需要5秒 2.客服端启动后去链接 ...

  7. react 16更新

    1.render新的返回类型 render方法支持两种新的返回类型:数组(由React元素组成)和字符串 2.错误处理 16之前,组件在运行期间如果执行出错,就会阻塞整个应用的渲染,这时候只能刷新页面 ...

  8. Parse-轻松构建移动APP的后台服务

    目前正在开发的产品告一段落,有时间总结下经验,也顺便分享一下我们主要使用的平台-Parse. 什么是Parse?  Parse是一群美国人开发的专为移动APP服务的云计算平台,与现有的其他云计算平台相 ...

  9. gulp是什么?

    什么是gulp? gulp初涉 1.什么是gulp? gulp是前端开发过程中一种基于流的代码构建工具,是自动化项目的构建利器:它不仅能对网站资源进行优化,而且在开发过程中很多重复的任务能够使用正确的 ...

  10. HDFS under replicated blocks

    under replicated blocks 解决: 找出没有复制的block: hdfs fsck / | grep 'Under replicated' | awk -F':' '{print ...