第一个简单netty程序
一个简单的netty的程序,主要是netty的客户端和服务端通信。
大部分说明都写在代码注释中
netty server
TimeServer
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioServerSocketChannel;
- public class TimeServer {
- public void bind(int port) throws Exception {
- // 配置 服务端的 NIO 线程组
- EventLoopGroup bossGroup = new NioEventLoopGroup();
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup)
- .channel(NioServerSocketChannel.class)
- .option(ChannelOption.SO_BACKLOG, 1024)
- .childHandler(new ChildChannelHandler());
- // 绑定端口,同步等待成功。
- ChannelFuture f = b.bind(port).sync();
- // 等待服务端监听端口关闭。
- f.channel().closeFuture().sync();
- } catch (Exception e) {
- // 退出,释放线程池资源
- bossGroup.shutdownGracefully();
- workerGroup.shutdownGracefully();
- }
- }
- private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
- @Override
- protected void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast(new TimeServerHandler());
- }
- }
- public static void main(String[] args) throws Exception{
- int port = 8080;
- if (args != null && args.length > 0) {
- try {
- port = Integer.valueOf(args[0]);
- } catch (NumberFormatException e) {
- }
- }
- new TimeServer().bind(port);
- }
- }
TimeServerHandler
- import io.netty.buffer.ByteBuf;
- import io.netty.buffer.Unpooled;
- import io.netty.channel.ChannelHandlerAdapter;
- import io.netty.channel.ChannelHandlerContext;
- import java.util.Date;
- public class TimeServerHandler extends ChannelHandlerAdapter {
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- ByteBuf buf = (ByteBuf) msg;
- byte[] req = new byte[buf.readableBytes()];
- buf.readBytes(req);
- String body = new String(req,"UTF-8");
- System.out.println("the time server receive order : " + body);
- String currentTime = "QUERY TIME ORDER"
- .equalsIgnoreCase(body) ? new Date(
- System.currentTimeMillis()).toString()
- : "BAD ORDER";
- ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
- ctx.write(resp);
- }
- /**
- * 当监听到端口时调用 channelActive 打印 "连接成功!"
- * @param ctx
- * @throws Exception
- */
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- System.out.println("连接成功!");
- }
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- ctx.flush();
- }
- /**
- * 当出现异常时,关闭连接
- */
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- System.out.println("出现异常,关闭");
- ctx.close();
- }
- }
netty client
TimeClient
- import io.netty.bootstrap.Bootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioSocketChannel;
- public class TimeClient {
- public void connect(int port, String host) throws Exception {
- //配置客户端 NIO 线程组
- EventLoopGroup group = new NioEventLoopGroup();
- try {
- Bootstrap b = new Bootstrap();
- b.group(group).channel(NioSocketChannel.class)
- .option(ChannelOption.TCP_NODELAY, true)
- .handler(new ChannelInitializer<SocketChannel>() {
- @Override
- protected void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast(new TimeClientHandler());
- }
- });
- // 发起异步连接操作
- ChannelFuture f = b.connect(host, port).sync();
- // 等待客户端链路关闭
- f.channel().closeFuture().sync();
- } finally {
- // 释放 NIO 线程组
- group.shutdownGracefully();
- }
- }
- public static void main(String[] args) throws Exception {
- int port = 8080;
- if (args != null && args.length > 0) {
- try {
- port = Integer.valueOf(args[0]);
- } catch (NumberFormatException e) {
- }
- }
- new TimeClient().connect(port, "127.0.0.1");
- }
- }
TimeClientHandler
- import io.netty.buffer.ByteBuf;
- import io.netty.buffer.Unpooled;
- import io.netty.channel.ChannelHandlerAdapter;
- import io.netty.channel.ChannelHandlerContext;
- import java.util.logging.Logger;
- public class TimeClientHandler extends ChannelHandlerAdapter {
- private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());
- private final ByteBuf firstMessage;
- public TimeClientHandler() {
- byte[] req = "QUERY TIME ORDER".getBytes();
- firstMessage = Unpooled.buffer(req.length);
- firstMessage.writeBytes(req);
- }
- /**
- * 当连接成功时,调用 writeAndFlush 发送 firstMessage 到服务端
- * @param ctx
- * @throws Exception
- */
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- ctx.writeAndFlush(firstMessage);
- }
- /**
- * 当服务端的有数据发送过来时,调用 channelRead 接受数据,并打印
- * @param ctx
- * @param msg
- * @throws Exception
- */
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- ByteBuf buf = (ByteBuf) msg;
- byte[] req = new byte[buf.readableBytes()];
- buf.readBytes(req);
- String body = new String (req,"UTF-8");
- System.out.println("Now is : " + body);
- }
- /**
- * 出现异常时,打印错误,并关闭
- * @param ctx
- * @param cause
- * @throws Exception
- */
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- logger.warning("Unexpected Exception from downstream : " + cause.getMessage());
- ctx.close();
- }
- }
个人感觉netty ,比java自带的NIO简单了很多,不过这只是一个简单小例子,后期可能会有更复杂的 。很期待后边的学习。
第一个简单netty程序的更多相关文章
- SpringMVC -- 第一个简单的程序
学习springMVC,我们来记录下第一个HelloWord的程序 首先.我们组织须要的jar包 commons-logging-1.1.3.jar spring-aop-4.1.7.RELEASE. ...
- Netty In Action中国版 - 第二章:第一Netty程序
本章介绍 获得Netty4最新的版本号 设置执行环境,以构建和执行netty程序 创建一个基于Netty的server和client 拦截和处理异常 编制和执行Nettyserver和client 本 ...
- MFC入门(一)-- 第一个简单的windows图形化界面小程序(打开计算器,记事本,查IP)
////////////////////////////////序//////////////////////////////// 大约三年前,学过一些简单的编程语言之后其实一直挺苦恼于所写的程序总是 ...
- 程序演示:C语言第一个简单实例
在信息化.智能化的世界里,可能很早很早 我们就听过许多IT类的名词,C语言也在其中,我们侃侃而谈,到底C程序是什么样子?让我们先看简单的一个例子: 1 2 3 4 5 6 7 8 9 #include ...
- Netty(1):第一个netty程序
为什么选择Netty netty是业界最流行的NIO框架之一,它的健壮型,功能,性能,可定制性和可扩展性都是首屈一指的,Hadoop的RPC框架Avro就使用了netty作为底层的通信框架,此外net ...
- 图解简单C程序的运行时结构
程序在内存中的存储分为三个区域,分别是动态数据区.静态数据区和代码区.函数存储在代码区,全局变量以及静态变量存储在静态数据区,而在程序执行的时候才会在动态数据区产生数据.程序执行的本质就是代码区的指令 ...
- 编写第一个微信小程序界面
编写第一个微信小程序界面 不忘初心,方得始终:初心易得,始终难守. 传统的 web 结构 小程序文件目录结构 小程序页面层级结构 编写第一个小程序 1. 创建小程序目录结构 2. 编写代码 welco ...
- MFC制作简单通讯录程序
学习c++和MFC一段时间了,苦于没有项目实战,所以自己写了一个简单的简单通讯录程序,以前用c#写简单很多,例程是这本书上的实例,我的第一个winform程序也是从这本书上学的,总结c#写的话更简单, ...
- 创建安全的 Netty 程序
1.使用 SSL/TLS 创建安全的 Netty 程序 SSL 和 TLS 是众所周知的标准和分层的协议,它们可以确保数据时私有的 Netty提供了SSLHandler对网络数据进行加密 使用Http ...
随机推荐
- Android开发 解决Installation failed due to XXX 问题
报错信息 Android studio 安装app的时候以下报错 Installation did not succeed. The application could not be installe ...
- leetcode-241-为运算表达式设置优先级*
题目描述: 方法:分治* class Solution: def diffWaysToCompute(self, input: str) -> List[int]: if input.isdig ...
- Java 虚拟机 - ClassLoader
ClassLoader定义 ClassLoader种类 BootStrapClassLoader无法在IDEA里面查看源代码,只能看JVM 源码才能找到. ExtClassLoader,会从Syste ...
- 把云数据库带回家!阿里云发布POLARDB Box数据库一体机
9月26日,2019杭州云栖大会上,阿里云宣布正式推出高性能数据库一体机——POLARDB Box,用户部署在自有数据中心即可享受云数据库的便捷体验,同时还为Oracle等传统数据库用户提供一键迁移功 ...
- DNS的解析过程
1.什么是DNS 在互联网上,唯一标识一台计算机的是IP地址,但是IP地址不方便记忆,通过一个域名对应一个IP地址,来达到找到IP地址的目的,那么DNS就是将域名转换成IP地址的过程. 2.DNS查询 ...
- python处理多线程之间事件通讯方法
一.什么是事件 每执行一个事情,肯定有该事情的执行后状态,那事件就是该事情发生的信号 在程序中,多线程之间需要通讯,而事件就是方便线程之间的通讯 案例: 1.服务器启动需要5秒 2.客服端启动后去链接 ...
- react 16更新
1.render新的返回类型 render方法支持两种新的返回类型:数组(由React元素组成)和字符串 2.错误处理 16之前,组件在运行期间如果执行出错,就会阻塞整个应用的渲染,这时候只能刷新页面 ...
- Parse-轻松构建移动APP的后台服务
目前正在开发的产品告一段落,有时间总结下经验,也顺便分享一下我们主要使用的平台-Parse. 什么是Parse? Parse是一群美国人开发的专为移动APP服务的云计算平台,与现有的其他云计算平台相 ...
- gulp是什么?
什么是gulp? gulp初涉 1.什么是gulp? gulp是前端开发过程中一种基于流的代码构建工具,是自动化项目的构建利器:它不仅能对网站资源进行优化,而且在开发过程中很多重复的任务能够使用正确的 ...
- HDFS under replicated blocks
under replicated blocks 解决: 找出没有复制的block: hdfs fsck / | grep 'Under replicated' | awk -F':' '{print ...