本篇文章是延续上一篇Netty文章,因此推荐先去看上一篇文章Netty(一),当然对Netty有一定认识略过。开始利用Netty创建一个简单的服务器
先上代码,运行后,再讲解!
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>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//重点 添加HttpServer
ch.pipeline().addLast("http-decoder",new HttpServerCodec());
//添加自定义的ChannelHandler
ch.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();
}
}
}
这里有几个基本的概念。
基本的 I/O 操作(bind()、connect()、read()和 write())依赖于底层网络传输所提
供的原语。在基于 Java 的网络编程中,其基本的构造是 class Socket。Netty 的 Channel 接口所提供的 API,大大地降低了直接使用 Socket 类的复杂性
EventLoop 定义了 Netty 的核心抽象,用于处理连接的生命周期中所发生的事件
用来初始化服务端可连接队列,服务端处理客户端连接请求是顺序处理的,同一时间只能处理一个客户端连接,多个客户端时,服务端将不能处理的客户端连接请求放在队列中等待处理,backlog参数指定了队列的大小
对应于套接字选项中的SO_REUSEADDR,这个参数表示允许重复使用本地地址和端口,该参数允许共用该端口。
对应于套接字选项中的SO_KEEPALIVE,该参数用于设置TCP连接,当设置该选项以后,连接会测试链接的状态,可能长时间没有数据交流的连接。当设置该选项以后,如果在两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文。
有了这些基本的概念后我们就开始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) ;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("客户端连上了...");
}
@Override
public 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());
//获取访问的url
String 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
*/
@Override
public 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
致此一个简单的请求响应的服务器就完成了,如理解有误,请指正,谢谢!!!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。