本篇文章是延续上一篇Netty文章,因此推荐先去看上一篇文章Netty(一),当然对Netty有一定认识略过。开始利用Netty创建一个简单的服务器 先上代码,运行后,再讲解!
NettyServer
package com.tanoak.demo3.server;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.HttpServerCodec;/** * @author tanoak@qq.com* @date 2018/7/1 0:45 * @Desc*/
public class HttpServer {public void start(final int port) throws Exception {EventLoopGroup boss = new NioEventLoopGroup();EventLoopGroup woker = new NioEventLoopGroup();ServerBootstrap serverBootstrap = new ServerBootstrap();try {serverBootstrap.channel(NioServerSocketChannel.class).group(boss, woker)//测试链接的状态.childOption(ChannelOption.SO_KEEPALIVE, true)// 用来初始化服务端可连接队列,服务端处理客户端连接请求是顺序处理的;指定队列的大小.option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {//重点 添加HttpServerch.pipeline().addLast("http-decoder",new HttpServerCodec());//添加自定义的ChannelHandlerch.pipeline().addLast(new HttpServerHandler());}});ChannelFuture future = serverBootstrap.bind(port).sync();future.channel().closeFuture().sync();} finally {boss.shutdownGracefully();woker.shutdownGracefully();}}public static void main(String[] args) {try{System.out.println("服务器正在启动中");new HttpServer().start(8080);}catch (Exception e){System.out.println("服务器启动失败");e.printStackTrace();}}
}复制代码
这里有几个基本的概念。
Channel — Socket ;
基本的 I/O 操作(bind()、connect()、read()和 write())依赖于底层网络传输所提
供的原语。在基于 Java 的网络编程中,其基本的构造是 class Socket。Netty 的 Channel 接口所提供的 API,大大地降低了直接使用 Socket 类的复杂性复制代码
EventLoop — 控制流、多线程处理、并发;
EventLoop 定义了 Netty 的核心抽象,用于处理连接的生命周期中所发生的事件复制代码
- 一个 EventLoopGroup 包含一个或者多个 EventLoop;
- 一个 EventLoop 在它的生命周期内只和一个 Thread 绑定;
- 所有由 EventLoop 处理的 I/O 事件都将在它专有的 Thread 上被处理;
- 一个 Channel 在它的生命周期内只注册于一个 EventLoop;
- 一个 EventLoop 可能会被分配给一个或多个 Channel。
ChannelFuture — 异步通知
Netty 中所有的 I/O 操作都是异步的。因为一个操作可能不会立即返回,所以我们需要一种用于在之后的某个时间点确定其结果的方法。为此,Netty 提供了ChannelFuture 接口
复制代码
ChannelHandler
Netty 的主要组件是 ChannelHandler,它充当了所有处理入站和出站数据的应用程序逻辑的容器
复制代码
ChannelPipeline
ChannelPipeline 提供了 ChannelHandler 链的容器,并定义了用于在该链上传播入站
和出站事件流的 API
复制代码
ChannelOption 部分参数
- ChannelOption.SO_BACKLOG
用来初始化服务端可连接队列,服务端处理客户端连接请求是顺序处理的,同一时间只能处理一个客户端连接,多个客户端时,服务端将不能处理的客户端连接请求放在队列中等待处理,backlog参数指定了队列的大小
- ChannelOption.SO_REUSEADDR
对应于套接字选项中的SO_REUSEADDR,这个参数表示允许重复使用本地地址和端口,该参数允许共用该端口。
- 、ChannelOption.SO_KEEPALIVE
对应于套接字选项中的SO_KEEPALIVE,该参数用于设置TCP连接,当设置该选项以后,连接会测试链接的状态,可能长时间没有数据交流的连接。当设置该选项以后,如果在两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文。
ChannelOption参数详解:传送门 有了这些基本的概念后我们就开始ChannelHandler的编写,这里是使用它的子类
ChannelHandler
package com.tanoak.demo3.server;import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;import java.util.HashMap;
import java.util.Map;/*** @author 656443534@qq.com* @date 2018/7/1 0:12 * @Desc*/
public class HttpServerHandler extends ChannelInboundHandlerAdapter {private static String yes = "<h1> this is yes Page </h1>";private static String helloPage = "<h1> this is Hello wolrd page </h1>";private String error = "<h1>404</h1>访问入径不存在";private static Map<String, String> mapUrl = new HashMap<>();static {mapUrl.put("hello",helloPage) ;mapUrl.put("yes",yes) ;}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("客户端连上了...");}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {if (msg instanceof HttpRequest) {HttpRequest request = (HttpRequest) msg;boolean keepaLive = HttpUtil.isKeepAlive(request);System.out.println("访问的方式是:" + request.method()+"类型");System.out.println("访问的URI:" + request.uri());//获取访问的urlString uri = request.uri().replace("/", "").trim();FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);if(mapUrl.get(uri)!=null){response.content().writeBytes(mapUrl.get(uri).getBytes());}else{response.content().writeBytes(error.getBytes());}//重定向处理if (response.status().equals(HttpResponseStatus.FOUND)) {response.headers().set(HttpHeaderNames.LOCATION, "https://www.baidu.com/");}response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());if (keepaLive) {response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);ctx.writeAndFlush(response);} else {ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);}}}/*** 有异常抛出时会调用。* @param ctx* @param cause*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {/*** 并且关闭该 Channel*/System.out.println("发生了异常");cause.printStackTrace();ctx.close() ;System.out.println("已关闭ChannelHandlerContext");}}
复制代码
可以看到主要的业务逻辑集中在channelRead(ChannelHandlerContext ctx, Object msg) ;这个方法主要还是使用Netty封装好的一些方法,指定Http的版本,状态码和accrpt