netty权威指南 ---------第三章 入门应用

要实现的功能: client端发送请求,server端接受请求,返回当前时间,client端将当前时间打印出来。

A :server端服务器

package com.xiaobing.netty.third;

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{

//服务端接受客户端的连接线程

EventLoopGroup bossGroup = new NioEventLoopGroup();

//网络读写线程

EventLoopGroup workerGroup = new NioEventLoopGroup();

//服务端辅助启动类

ServerBootstrap b = new ServerBootstrap();

try {

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();

}finally{

bossGroup.shutdownGracefully();

workerGroup.shutdownGracefully();

}

}

//网络IO处理类

private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{

@Override

protected void initChannel(SocketChannel arg0) throws Exception {

arg0.pipeline().addLast(new TimeServerHandler());

}

}

public static void main(String[] args) throws Exception {

int port = 8080;

new TimeServer().bind(port);

}

}

B:server端 处理类

package com.xiaobing.netty.third;

import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

//对网络事件进行读写

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 currentTimeString  = "QUERY TIME ORDER".equalsIgnoreCase(body)?new java.util.Date(System.currentTimeMillis()).toString() :"BAD ORDER";

//应答消息

ByteBuf resp = Unpooled.copiedBuffer(currentTimeString.getBytes());

ctx.write(resp);

}

@Override

public void channelReadComplete(ChannelHandlerContext ctx){

//将消息发送队列的消息写入socketchannel中

ctx.flush();

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){

//发生异常时,关闭ctx

ctx.close();

}

}

C:客户端 请求

package com.xiaobing.netty.third;

import java.security.acl.Group;

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{

EventLoopGroup group = new NioEventLoopGroup();

try{

//客户端启动辅助类

Bootstrap b = new Bootstrap();

b.group(group).channel(NioSocketChannel.class)

.option(ChannelOption.TCP_NODELAY, true)

.handler(new ChannelInitializer<SocketChannel>() {

//在初始化时将channelHandler 设置到channelpipeline中

@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{

group.shutdownGracefully();

}

}

public static void main(String[] args) throws Exception {

int port = 8080;

new TimeClient().connect(port, "127.0.0.1");

}

}

D 客户端对server端返回值的处理

package com.xiaobing.netty.third;

import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

//对网络事件进行读写

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 currentTimeString  = "QUERY TIME ORDER".equalsIgnoreCase(body)?new java.util.Date(System.currentTimeMillis()).toString() :"BAD ORDER";

//应答消息

ByteBuf resp = Unpooled.copiedBuffer(currentTimeString.getBytes());

ctx.write(resp);

}

@Override

public void channelReadComplete(ChannelHandlerContext ctx){

//将消息发送队列的消息写入socketchannel中

ctx.flush();

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){

//发生异常时,关闭ctx

ctx.close();

}

}

时间: 2024-08-05 00:12:07

netty权威指南 ---------第三章 入门应用的相关文章

netty权威指南--------第四章TCP粘包/拆包问题

第三章中的示例用于功能测试一般没有问题,但当压力上来或者发送大报文时,就会存在粘包/拆包问题. 这时就需要使用LineBasedFrameDecoder+StringDecoder client端请求改为连续的100次 package com.xiaobing.netty.fourth; import java.net.SocketAddress; import org.omg.CORBA.Request; import io.netty.buffer.ByteBuf; import io.ne

Netty权威指南

Netty权威指南(异步非阻塞通信领域的经典之作,国内首本深入剖析Netty的著作,全面系统讲解原理.实战和源码,带你完美进阶Netty工程师.) 李林锋 著   ISBN 978-7-121-23343-2 2014年6月出版 定价:79.00元 524页 16开 编辑推荐 - 资深一线专家诚意之作,总结多年实践经验,带你全面掌握Java高并发异步通信的首选框架——Netty. - Facebook.阿里巴巴.1号店.并发编程网.JBoss等多位资深技术专家联名力荐. <Netty权威指南>

电子书 netty权威指南第2版.pdf

<Netty quanwei指南(第2 版)>是异步非阻塞通信领域的经典之作,基于全新版本的Netty 5.0 编写,是国内首本深入介绍Netty 原理和架构的书籍,也是作者多年实战经验的总结和浓缩.内容不仅包含Java NIO入门知识.Netty 的基础功能开发指导.编解码框架定制等,还包括私有协议栈定制和开发.Netty 核心类库源码分析,以及Netty 的架构剖析. 作者简介 李林峰,Netty中国推广者,现华为技术有限公司平台中间件架构与设计部设计师,公司总裁技术创新奖获得者.长期从事

《Netty权威指南》私有协议开发的可运行源代码分享

之前看了<Netty权威指南>一书,第14章用整个章节介绍了如何设计和实现一个简单的私有协议,内容很好,但是作者提供的代码片段有很多错误,根本不可能正确编译. 比如MarshallingEncoder这个类是Netty提供了JBoss Marshalling的一个适配类,它的encode方法是protected,不是public,并且其中用到的ChannelBufferByteOutput类是包类可见,外部无法引用的.Netty只所以这么设计,是因为这个工具类不能直接被外部使用,只是给它内部

HTTP权威指南:第二章

URL概览 前面提到,URL资源是HTTP协议所使用的寻找资源位置的定位符.分为三个部分,主要的结构是: 方案://服务器/路径 这种结构使得网络上的每一个资源都只有唯一的命名方法,从而使得浏览器可以统一对不同的资源进行处理,而不是依赖不同的软件.URL可以从以下几个部分去了解: 语法 快捷方式 特殊字符 方案 最后,我们还会展望未来,看看URN--URL的下一代. 一.语法 URL语法是跟对方案而变化的,但是这些变化总是建立在URL语法的9个组件组成的通用格式之上的.这个通用格式是: <sch

JavaScript权威指南第13章 web浏览器中的javascript

13.1 客户端javascript window对象是所有的客户端javascript特性和api的主要接入点.表示浏览器的一个窗口,可以通过window对象来引用它. window 的方法 alert() prompt() confirm() 13.2 在html里嵌入javascript 4种方法: 内联:放置在<script></script>标签之中 外部引入:<script src="   "></script> html程序

JavaScript权威指南第04章 表达式和运算符

www.qdmm.com/BookReader/1845423,31051137.aspx www.qdmm.com/BookReader/1845423,31073665.aspx www.qdmm.com/BookReader/1845423,31088923.aspx www.qdmm.com/BookReader/1845423,31104070.aspx www.qdmm.com/BookReader/1845423,31114804.aspx www.qdmm.com/BookRea

JavaScript权威指南第01章 JavaScript 概述

JavaScript 概述 html +css +JavaScript = 网页三大利器 特点: 健壮性 高效性 通用性 1.JavaScript  语言核心 2.客户端JavaScript JavaScript权威指南第01章 JavaScript 概述

JavaScript权威指南第02章 词法结构

词法结构 2.1字符集 JavaScript 是Unicode字符集编写,几乎支持地球上所有的语言. 2.1.1区分大小写 javascript是区分大小写的语言. 2.1.2 空格.换行符和格式控制符 javascript会忽略标识之间的空格符.换行符.通过空格和换行可以大大地提高代码的可读性.当需要使用空格和换行符时,使用Unicode的转义来实现. 2.2注释 单行注释     //这里是单行注释 多行注释    /**多行注释 */ 2.3直接量 在程序中能够直接使用的量,比如数字,字符