新建maven项目,添加依赖

<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0..Alpha1</version>
</dependency>

TimeServer

package com.zhen.netty1129;

import java.awt.Event;
import java.net.Socket; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoop;
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线程组
//NioEventLoopGroup是个线程组,它包含了一组NIO线程,专门用于网络事件的处理,实际上它们就是Reactor线程组
//bossGroup用于服务端接受客户端的连接
EventLoopGroup bossGroup = new NioEventLoopGroup();
//workerGroup进行SocketChannel的网络读写
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度
ServerBootstrap bootstrap = new ServerBootstrap();
//将两个NIO线程组当作入参传递到ServerBootstrap
bootstrap.group(bossGroup, workerGroup)
//设置创建的Channel为NioServerSocketChannel,它的功能对应于JDK NIO类库中的ServerSocketChannel类。
.channel(NioServerSocketChannel.class)
//配置NioServerSocketChannel的TCP参数,此处将它的backlog设置为1024
.option(ChannelOption.SO_BACKLOG, )
//绑定I/O事件的处理类ChildChannelHandler,它的作用类似于Reactor模式中的Handler类,主要用于处理网络I/O事件,例如记录日志、对消息进行编解码等
.childHandler(new ChildChannelHandler());
//调用bind方法绑定监听端口,随后,调用它的同步阻塞方法sync等待绑定操作完成。
//完成之后Netty会返回一个ChannelFuture,它的功能类似于JDK的java.util.concurrent.Future,主要用于异步操作的通知回调
ChannelFuture future = bootstrap.bind(port).sync();
//等待服务端监听端口关闭,等待服务端链路关闭之后main函数才退出
future.channel().closeFuture().sync();
} finally {
//优雅退出,释放线程池资源
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 = ;
if (args != null && args.length > ) {
try {
port = Integer.valueOf(args[]);
} catch (Exception e) {
e.printStackTrace();
}
}
new TimeServer().bind(port);
}
}

TimeServerHandler

package com.zhen.netty1129;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; //TimeServerHandler 继承自ChannelHandlerAdapter,它用于对网络事件进行读写操作
public class TimeServerHandler extends ChannelHandlerAdapter{ @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//将msg转换成Netty的ByteBuf对象。ByteBuf类似于jdk中的java.nio.ByteBuffer对象,不过它提供了更加强大和灵活的功能
ByteBuf buf = (ByteBuf) msg;
//通过ByteBuf的readableBytes方法可以获取缓冲区可读的字节数,根据可读的字节数创建byte数组
byte[] req = new byte[buf.readableBytes()];
//通过ByteBuf的readBytes方法将缓冲区中的字节数据复制到新建的byte数组中
buf.readBytes(req);
//通过new String构造函数获取请求消息
String body = new String(req, "UTF-8");
System.out.println("The time server receive order : " + body);
//对请求消息进行判断,如果是QUERY TIME ORDER则创建应答消息
String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ?
new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
//通过ChannelHandlerContext的write方法异步发送应答消息给客户端
ctx.write(resp);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//将消息发送队列中的消息写入到SocketChannel中发送给对方
//从性能角度考虑,为了防止频繁的唤醒Selector进行消息发送,Netty的write方法并不直接将消息写入SocketChannel中
//调用write方法只是把待发送的消息放到发送缓冲数组中,再通过调用flush方法,将发送缓冲区中的消息全部写到SocketChannel中。
ctx.flush();
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//当发生异常时,关闭ChannelHandlerContext,释放和ChannelHandlerContext相关联的句柄等资源
ctx.close();
}
}

TimeClient

package com.zhen.netty1129;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
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.nio.NioSocketChannel; public class TimeClient { public void connect(int port,String host) throws Exception{
//配置客户端NIO线程组,客户端处理I/O读写的NioEventLoopGroup线程组
EventLoopGroup group = new NioEventLoopGroup();
try {
//客户端辅助启动类Bootstrap
Bootstrap bootstrap = new Bootstrap();
//设置线程组
bootstrap.group(group)
//与服务端不同的是,它的channel需要设置为NioSocketChannel
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
//然后为其添加Handler,此处为了简单直接创建匿名内部类,实现initChannel方法
//作用是当创建NioSocketChannel成功之后,在进行初始化时,将它的ChannelHandler设置到ChannelPipeline中,用于处理网络I/O事件
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new TimeClientHandler());
}
});
//调用connect发起异步连接操作,然后调用sync同步方法等待连接成功。
ChannelFuture future = bootstrap.connect(host, port).sync();
//等待客户端链路关闭,当客户端连接关闭之后,客户端主函数退出,退出之前释放NIO线程组的资源
future.channel().closeFuture().sync();
} finally {
//优雅退出,释放NIO线程组
group.shutdownGracefully();
}
} public static void main(String[] args) throws Exception{
int port = ;
String host = "127.0.0.1";
if (args != null && args.length > ) {
try {
port = Integer.valueOf(args[]);
} catch (Exception e) {
e.printStackTrace();
}
}
new TimeClient().connect(port, host);
} }

TimeClientHandler

package com.zhen.netty1129;

import java.util.logging.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; 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);
} //当客户端和服务端TCP链路建立成功之后,Netty的NIO线程会调用channelActive方法,发送查询时间的指令给服务端
//调用ChannelHandlerContext的writeAndFlush方法将请求消息发送给客户端
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(firstMessage);
} //当客户端返回应答消息,channelRead方法被调用
@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);
} //发生异常时,释放客户端资源
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.warning("Unexpected exception from downstream : " + cause.getMessage());
ctx.close();
} }

先运行TimeServer,再运行TimeClient

Netty入门例子的更多相关文章

  1. Netty入门

    一.NIO Netty框架底层是对NIO的高度封装,所以想要更好的学习Netty之前,应先了解下什么是NIO - NIO是non-blocking的简称,在jdk1.4 里提供的新api,他的他的特性 ...

  2. netty入门(一)

    1. netty入门(一) 1.1. 传统socket编程 在任何时候都可能有大量的线程处于休眠状态,只是等待输入或者输出数据就绪,这可能算是一种资源浪费. 需要为每个线程的调用栈都分配内存,其默认值 ...

  3. Netty入门(二)之PC聊天室

    参看Netty入门(一):Netty入门(一)之webSocket聊天室 Netty4.X下载地址:http://netty.io/downloads.html 一:服务端 1.SimpleChatS ...

  4. Netty入门(一)之webSocket聊天室

    一:简介 Netty 是一个提供 asynchronous event-driven (异步事件驱动)的网络应用框架,是一个用以快速开发高性能.高可靠性协议的服务器和客户端. 换句话说,Netty 是 ...

  5. Netty 系列(三)Netty 入门

    Netty 系列(三)Netty 入门 Netty 是一个提供异步事件驱动的网络应用框架,用以快速开发高性能.高可靠性的网络服务器和客户端程序.更多请参考:Netty Github 和 Netty中文 ...

  6. Netty入门 - 秒懂

    目录 Netty 入门 前言: 建立项目 编写一个Discard Handler 处理器 编写一个Discard 服务器 线程组 启动帮助类 设置Channel 通道的选项 测试:发送消息到Disca ...

  7. 【Bootstrap Demo】入门例子创建

    本文简单介绍下如何来使用 Bootstrap,通过引入 Bootstrap,来实现一个最基本的入门例子. 在前一篇博文[Bootstrap]1.初识Bootstrap 基础之上,我们完全可以更加方便快 ...

  8. 【Bootstrap】入门例子创建

    本文简单介绍下如何来使用 Bootstrap,通过引入 Bootstrap,来实现一个最基本的入门例子. 在前一篇博文[Bootstrap]1.初识Bootstrap 基础之上,我们完全可以更加方便快 ...

  9. spring boot入门例子

    最近学习spring boot,总结一下入门的的基础知识 1新建maven项目,修改pom.xml <project xmlns="http://maven.apache.org/PO ...

随机推荐

  1. angularjs中的路由介绍详解 ui-route

    这篇文章主要介绍了Angularjs中UI Router全攻略,涉及到angularjs ui router的基本用法,需要的朋友参考下吧   首先给大家介绍angular-ui-router的基本用 ...

  2. mysql合并同一列的值

      我有例如以下的查询条件显示: 我希望终于显示的效果如图: 将id同样的group_name合并到一行.实现方法:在group_name前面加keywordgroup_concat.然后在sql语句 ...

  3. 浅谈&quot;壳&quot;(一)

    壳,即坚硬的外皮,当壳的厚度与其曲面率半径的比值小于0.5时.称为"薄壳".反之称为"厚壳".由壳演化来的胸甲,盾牌. 在计算机这个注重创意又不失从文化科技中汲 ...

  4. hdu 1398 Square Coins 分钱币问题

    Square Coins Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit ...

  5. eclipse导入svn工程,在文件夹里面不展示svn工程图标

    原因:没有安装subclipse插件 解决方法:在marketplace中搜索插件名字:subclipse,点击安装,或者在instal new software中输入插件名字,安装完成之后,在文件夹 ...

  6. oracle中can not set解决方法

    原因:set autotrace on和set trimspool on在pl\sql中使用不了 解决方法:在window环境中,使用cmd命令,sqlplus user_name/password@ ...

  7. NYOJ 613 免费馅饼

    免费馅饼 时间限制:1000 ms  |  内存限制:65535 KB 难度:3 描写叙述 都说天上不会掉馅饼,但有一天gameboy正走在回家的小径上,忽然天上掉下大把大把的馅饼.说来gameboy ...

  8. VC++ 读写注冊表,注冊文件图标关联

    #include <string> #include <iostream> #include <Windows.h> #include <shlobj.h&g ...

  9. c3p0;jdbc;dbcp;mybatis;ubutils;

    [说明]今天还是完成了一定东西的,上午是jdbc的测试,下午是 数据库连接池 和 dbutils 的测试,晚上是mybatis的测试,都是找了一些网上的例子运行了一下,解决出现的问题. 一:今日完成 ...

  10. 股神小L 2016Vijos省选集训 day1

    股神小L (stock.c/pas/cpp)============================ 小L厌倦了算法竞赛,希望到股市里一展身手.他凭借自己还行的计算机功底和可以的智商,成功建立一个模型 ...