博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Netty框架学习之路(二)—— 一个简单的Netty程序
阅读量:4223 次
发布时间:2019-05-26

本文共 3942 字,大约阅读时间需要 13 分钟。

前言

上一篇博文中主要介绍了三种IO模式,Netty是一个高性能、异步事件驱动的Java NIO框架,本文以一个简单的Netty程序带领大家先来领略一下Netty的风采,程序的功能主要是获取当前的服务器时间。

客户端

TimeClient.java

public class TimeClient {    public void connect(int port, String host) throws Exception{        EventLoopGroup group = new NioEventLoopGroup();        try {            Bootstrap b = new Bootstrap();            b.group(group).channel(NioSocketChannel.class)                    .option(ChannelOption.TCP_NODELAY, true)                    .handler(new ChannelInitializer
() { @Override public void initChannel(SocketChannel ch) throws Exception{ ch.pipeline().addLast(new TimeClientHandler()); } }); ChannelFuture f = b.connect(host, port).sync(); f.channel().closeFuture().sync(); }finally { group.shutdownGracefully(); } } public static void main(String[] args) throws Exception{ int port = 8800; new TimeClient().connect(port, "localhost"); }}

TimeClientHandler.java

public class TimeClientHandler extends ChannelHandlerAdapter {
private final ByteBuf firstMessage; public TimeClientHandler(){ byte[] req = "QUERY TIME ORDER".getBytes(); firstMessage = Unpooled.buffer(req.length); firstMessage.writeBytes(req); } public void channelActive(ChannelHandlerContext ctx){ ctx.writeAndFlush(firstMessage); } 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); } public void exceptionCaught(ChannelHandlerContext ctx) throws Exception{ ctx.close(); }}

服务端

TimeServer.java

public class TimeServer {
public void bind(int port) throws Exception{ 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 ChannelInitializer
(){ @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new TimeServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); }finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception{ int port = 8800; new TimeServer().bind(port); }}

TimeServerHandler.java

public class TimeServerHandler extends ChannelHandlerAdapter {
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); } public void channelReadComplete(ChannelHandlerContext ctx) throws Exception{ ctx.flush(); } public void exceptionCaught(ChannelHandlerContext ctx) throws Exception{ ctx.close(); }}

运行结果

客户端

这里写图片描述
服务端
这里写图片描述

总结

“蚊子虽小,五脏俱全”。上述代码功能虽然简单,但是却涵盖了例如Channel、ChannelPipeline、EventLoopGroup、EventLoopGroup等Netty最核心的组件,这些核心组件会在后续的博文中详细讲述。

你可能感兴趣的文章
Conclusion for Constructors,Destructors,and Assignment Operators
查看>>
《浪潮之巅》1 AT&T
查看>>
《浪潮之巅》2蓝色巨人 IBM公司
查看>>
《浪潮之巅》3水果公司的复兴
查看>>
《浪潮之巅》4计算机工业的生态链
查看>>
《浪潮之巅》5奔腾的芯 英特尔公司
查看>>
python语言程序设计基础笔记(三)从题目到方案
查看>>
读取txt文件出现出现多余空行问题
查看>>
从理论到实践开发自己的聊天机器人
查看>>
@***装饰器(python)
查看>>
2.3 WSN的MAC协议
查看>>
栈与队列的应用——计算表达式的值
查看>>
BFS——求矩阵中“块”的个数
查看>>
BFS——走迷宫的最小步数
查看>>
并查集——好朋友
查看>>
关键路径
查看>>
Web前端学习笔记——JavaScript之事件详解
查看>>
Web前端学习笔记——JavaScript之事件、创建元素、节点操作
查看>>
Web前端学习笔记——JavaScript之正则表达式、伪数组、垃圾回收
查看>>
Web前端学习笔记——JavaScript 之继承、函数进阶
查看>>