前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java学习笔记—开源框架Netty的简单使用

Java学习笔记—开源框架Netty的简单使用

作者头像
慕容千语
发布2019-06-13 12:12:40
5910
发布2019-06-13 12:12:40
举报
1:什么是Netty

Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。

Netty是一个基于NIO的客户,服务器端编程框架,使用Netty可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户,服务端应用。

Netty相当简化和流线化了网络应用的编程开发过程,例如,TCP和UDP的socket服务开发。

Netty是一个吸收了多种协议的实现经验,这些协议包括FTP,SMTP,HTTP,各种二进制,文本协议,并经过相当精心设计的项目,最终,Netty 成功的找到了一种方式,在保证易于开发的同时还保证了其应用的性能,稳定性和伸缩性。

官网地址:http://netty.io/index.html

2:Netty的特性

设计

统一的API,适用于不同的协议(阻塞和非阻塞)

基于灵活、可扩展的事件驱动模型

高度可定制的线程模型

可靠的无连接数据Socket支持(UDP)

性能

更好的吞吐量,低延迟

更省资源

尽量减少不必要的内存拷贝

安全

完整的SSL/TLS和STARTTLS的支持

能在Applet与Android的限制环境运行良好

健壮性

不再因过快、过慢或超负载连接导致OutOfMemoryError

不再有在高速网络环境下NIO读写频率不一致的问题

易用

完善的JavaDoc,用户指南和样例

简洁简单

3:Netty基本架构图
4:简单例子(本文中netty的版本是netty-all-4.0.29)

去官网下载jar http://netty.io/index.html 或者可以使用maven

io.netty netty-all 4.0.29.Final

以HTTP协议举例

service代码

package com.demo.http;

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;

import io.netty.handler.codec.http.HttpRequestDecoder;

import io.netty.handler.codec.http.HttpResponseEncoder;

public class HttpServer {

public void start(int port) throws Exception {

EventLoopGroup bossGroup = new NioEventLoopGroup();

EventLoopGroup workerGroup = new NioEventLoopGroup();

try {

ServerBootstrap b = new ServerBootstrap();

b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)

.childHandler(new ChannelInitializer() {

@Override

public void initChannel(SocketChannel ch) throws Exception {

// server端发送的是httpResponse,所以要使用HttpResponseEncoder进行编码

ch.pipeline().addLast(new HttpResponseEncoder());

// server端接收到的是httpRequest,所以要使用HttpRequestDecoder进行解码

ch.pipeline().addLast(new HttpRequestDecoder());

ch.pipeline().addLast(new HttpServerInboundHandler());

}

}).option(ChannelOption.SO_BACKLOG, 128)

.childOption(ChannelOption.SO_KEEPALIVE, true);

ChannelFuture f = b.bind(port).sync();

f.channel().closeFuture().sync();

} finally {

workerGroup.shutdownGracefully();

bossGroup.shutdownGracefully();

}

}

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

HttpServer server = new HttpServer();

System.out.println("Http Server listening on 8844 ...");

server.start(8844);

}

}

package com.demo.http;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;

import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.ChannelInboundHandlerAdapter;

import io.netty.handler.codec.http.DefaultFullHttpResponse;

import io.netty.handler.codec.http.FullHttpResponse;

import io.netty.handler.codec.http.HttpContent;

import io.netty.handler.codec.http.HttpHeaders;

import io.netty.handler.codec.http.HttpHeaders.Values;

import io.netty.handler.codec.http.HttpRequest;

public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter {

private HttpRequest request;

@Override

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

if (msg instanceof HttpRequest) {

request = (HttpRequest) msg;

String uri = request.getUri();

System.out.println("Uri:" + uri);

}

if (msg instanceof HttpContent) {

HttpContent content = (HttpContent) msg;

ByteBuf buf = content.content();

System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));

buf.release();

String res = "www.ccblog.cn";

FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,

Unpooled.wrappedBuffer(res.getBytes("UTF-8")));

response.headers().set(CONTENT_TYPE, "text/plain");

response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

if (HttpHeaders.isKeepAlive(request)) {

response.headers().set(CONNECTION, Values.KEEP_ALIVE);

}

ctx.write(response);

ctx.flush();

}

}

public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

ctx.flush();

}

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

System.out.println(cause.getMessage());

ctx.close();

}

}

客户端访问

第一中执行上面的main方法后 在浏览器里面直接输入

http://127.0.0.1:8844/ 你可以看到 www.ccblog.cn 内容。

第二种采用java编写客户端

代码如下

package com.demo.http;

import io.netty.bootstrap.Bootstrap;

import io.netty.buffer.Unpooled;

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;

import io.netty.handler.codec.http.DefaultFullHttpRequest;

import io.netty.handler.codec.http.HttpHeaders;

import io.netty.handler.codec.http.HttpMethod;

import io.netty.handler.codec.http.HttpRequestEncoder;

import io.netty.handler.codec.http.HttpResponseDecoder;

import io.netty.handler.codec.http.HttpVersion;

import java.net.URI;

public class HttpClient {

public void connect(String host, int port) throws Exception {

EventLoopGroup workerGroup = new NioEventLoopGroup();

try {

Bootstrap b = new Bootstrap();

b.group(workerGroup);

b.channel(NioSocketChannel.class);

b.option(ChannelOption.SO_KEEPALIVE, true);

b.handler(new ChannelInitializer() {

@Override

public void initChannel(SocketChannel ch) throws Exception {

// 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码

ch.pipeline().addLast(new HttpResponseDecoder());

// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码

ch.pipeline().addLast(new HttpRequestEncoder());

ch.pipeline().addLast(new HttpClientInboundHandler());

}

});

// Start the client.

ChannelFuture f = b.connect(host, port).sync();

URI uri = new URI("http://127.0.0.1:8844");

String msg = "Are you ok?";

DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,

uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));

// 构建http请求

request.headers().set(HttpHeaders.Names.HOST, host);

request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);

request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());

// 发送http请求

f.channel().write(request);

f.channel().flush();

f.channel().closeFuture().sync();

} finally {

workerGroup.shutdownGracefully();

}

}

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

HttpClient client = new HttpClient();

client.connect("127.0.0.1", 8844);

}

}

package com.demo.http;

import io.netty.buffer.ByteBuf;

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.ChannelInboundHandlerAdapter;

import io.netty.handler.codec.http.HttpContent;

import io.netty.handler.codec.http.HttpHeaders;

import io.netty.handler.codec.http.HttpResponse;

public class HttpClientInboundHandler extends ChannelInboundHandlerAdapter {

@Override

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

if (msg instanceof HttpResponse) {

HttpResponse response = (HttpResponse) msg;

System.out.println("CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));

}

if (msg instanceof HttpContent) {

HttpContent content = (HttpContent) msg;

ByteBuf buf = content.content();

System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));

buf.release();

}

}

}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.01.24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1:什么是Netty
  • 2:Netty的特性
  • 3:Netty基本架构图
  • 4:简单例子(本文中netty的版本是netty-all-4.0.29)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档