Netty 之多协议开发
经过了这么多篇文章,其实大家也肯定知道,Netty
主要是在 OSI
七层网络层的应用层进行数据处理的(因为 Socket 是出于传输层以上的东西,是应用层与传输层的一个抽象层
)。所以肯定明白 Netty
在协议这方面肯定是能够掌控的。
HTTP
说到网络协议,相信大家最熟悉的协议也就是 HTTP
协议了。HTTP
协议是建立在 TCP
传输协议上的应用层协议,属于应用层的面向对象协议。由于简捷,快速的方式,适用于分布式超媒体信息系统。
HTTP 特点
HTTP
协议主要有如下特点:
- 支持 CS 模式。
- 简洁。客户端向服务端请求只需要指定服务 URL,携带必要的请求参数或者消息体。
- 灵活。
HTTP
允许传输任意类型的数据对象,传输内容类型是 HTTP 消息头的Content-type
加以标记。 - 高效。客户端和服务端之间是一种一次性连接,它限制了每次连接只处理一个请求。当服务器返回本次请求的应答后便立即关闭连接,等待下一次重新建立连接。这样做是为了顾虑到日后介入千万个用户,及时地释放连接可以大大提高服务器的执行效率。
- 无状态。
HTTP
协议是无状态协议,指的是对于事务处理没有任何记忆能力。缺少记忆能力的后果就是导致后续的处理需要之前的信息,则客户端必须携带重传,这样可能导致每次连接传送的数据亮增大。另一方面,在服务器不需要先前信息时它的应答较快,负载较轻。
知道完特点后,我再简单介绍一下 HTTP
的数据构成,这样有助于我们理解下面的内容。
HTTP 数据构成
使用 Netty 搭建 HTTP 服务器
由于这次搭建的是 Http 服务器,那说明我们可以通过浏览器作为客户端来进行访问服务端了,也就是我们不需要去写客户端代码。
服务端
首先编写的是服务端 HttpFileServer.java
public class HttpFileServer {
//项目访问上下文
private static final String DEFAULT_URL = "/httpProject";
public void run(final int port, final String url) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//http 解码
ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
//http 接收编码
ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
//http 编码工具类
ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
//chunked 操作
ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
//文件系统业务逻辑
ch.pipeline().addLast("fileServerHandler", new HttpFileServerHander(url));
}
});
ChannelFuture f = serverBootstrap.bind("127.0.0.1", port).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
new HttpFileServer().run(8080, DEFAULT_URL);
}
}
注意到这次的服务端代码在 ChannelInitializer
的初始化跟以往有点不同,这次上初始了多个 handler。下面我简单说下它们的用法。
类名 | 说明 |
---|---|
HttpRequestDecoder | 负责将 ByteBuf 解码成为 HttpRequest 和 HttpContent 内容 |
HttpObjectAggregator | 负责将 Http 信息和内容封装成为单个 FullHttpRequest |
HttpResponseEncoder | 对服务端返回的内容进行编码 |
ChunkedWriteHandler | 支持异步大数据量写入避免内存超出 |
然后我们开始写 HttpFileServerHander.java
public class HttpFileServerHander extends
SimpleChannelInboundHandler<FullHttpRequest> {
private String url;
public HttpFileServerHander(String url) {
this.url = url;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
//由于我们上面使用 netty 的解码器 FullHttpRequest 来封装信息
if (!request.getDecoderResult().isSuccess()) {
sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
//如果不是 get 方法则抛弃
if (request.getMethod() != HttpMethod.GET) {
sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
//获取访问的路径
final String uri = request.getUri();
//解码路径
final String path = sanitizeUri(uri);
//如果路径为空,说明错误请求
if (path == null) {
sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
//新建文件对象
File file = new File(path);
//如果不在,返回 404
if (file.isHidden() || !file.exists()) {
sendError(ctx, HttpResponseStatus.NOT_FOUND);
return;
}
//如果是目录就循环目录内容返回
if (file.isDirectory()) {
if (uri.endsWith("/")) {
sendListing(ctx, file);
} else {
sendRedirect(ctx, uri + '/');
}
return;
}
//如果是文件就
if (!file.isFile()) {
sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
//具备权限访问的文件
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "r");
}catch (FileNotFoundException e) {
sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
long fileLength = randomAccessFile.length();
//新建一个 DefaultFullHttpResponse
HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
//设置文件长度
HttpHeaders.setContentLength(response, fileLength);
setContentTypeHeader(response, file);
if (HttpHeaders.isKeepAlive(request)) {
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
}
//ctx写入 response
ctx.write(response);
//设置写入文件的 listener
ChannelFuture sendFileFuture;
sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192), ctx.newProgressivePromise());
//设置监听仅需的的 Listener
sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
@Override
public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) throws Exception {
if (total < 0) { // total unknown
System.err.println("Transfer progress: " + progress);
} else {
System.err.println("Transfer progress: " + progress + " / " + total);
}
}
@Override
public void operationComplete(ChannelProgressiveFuture future) throws Exception {
System.out.println("Transfer complete.");
}
});
//最后输出空内容
ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
if (HttpHeaders.isKeepAlive(request)) {
lastContentFuture.addListener(ChannelFutureListener.CLOSE);
}
}
private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");
//解析 url
private String sanitizeUri(String uri) {
try {
uri = URLDecoder.decode(uri, "UTF-8");
} catch (UnsupportedEncodingException e) {
try {
uri = URLDecoder.decode(uri, "ISO-8859-1");
} catch (UnsupportedEncodingException e1) {
throw new Error();
}
}
if (!uri.startsWith(url)) {
return null;
}
if (!uri.startsWith("/")) {
return null;
}
uri = uri.replace('/', File.separatorChar);
if (uri.contains(File.separator + '.')
|| uri.contains('.' + File.separator) || uri.startsWith(".")
|| uri.endsWith(".") || INSECURE_URI.matcher(uri).matches()) {
return null;
}
return System.getProperty("user.dir") + File.separator + uri;
}
private static final Pattern ALLOWED_FILE_NAME = Pattern.compile("[A-Za-z0-9][-_A-Za-z0-9\\.]*");
//渲染画面
private static void sendListing(ChannelHandlerContext ctx, File dir) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
StringBuilder buf = new StringBuilder();
String dirPath = dir.getPath();
buf.append("<!DOCTYPE html>\r\n");
buf.append("<html><head><title>");
buf.append(dirPath);
buf.append(" 目录:");
buf.append("</title></head><body>\r\n");
buf.append("<h3>");
buf.append(dirPath).append(" 目录:");
buf.append("</h3>\r\n");
buf.append("<ul>");
buf.append("<li>链接:<a href=\"../\">..</a></li>\r\n");
for (File f : dir.listFiles()) {
if (f.isHidden() || !f.canRead()) {
continue;
}
String name = f.getName();
if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
continue;
}
buf.append("<li>链接:<a href=\"");
buf.append(name);
buf.append("\">");
buf.append(name);
buf.append("</a></li>\r\n");
}
buf.append("</ul></body></html>\r\n");
ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
response.content().writeBytes(buffer);
buffer.release();
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
//重定向
private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
response.headers().set(HttpHeaderNames.LOCATION, newUri);
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
//发送错误信息
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
Unpooled.copiedBuffer("failures: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
//设置头部内容
private static void setContentTypeHeader(HttpResponse response, File file) {
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
response.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath()));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
if (ctx.channel().isActive()) {
sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
}
}
客户端
客户端在这个例子中并不存在。因为我们电脑的浏览器就是一个一个客户端,它们底层也是通过 Socket
来与服务端进行交互的,原理都是一样的。所以我们只需要访问以下地址:
结语
这篇文章简单介绍了一下 Http
以及讲如何使用 Netty
结合 Http
协议实现一个小服务端。当然,其实我们可以知道,搞定了协议相当于搞定了一个服务器应用的一半。所以我们可以在这个小服务端上面继续添加新的内容。例如说,扩展一个 IOC 容器,或者是接入多种模板渲染的方式 HTML
/ XML
/ JSON
等等,甚至可以再实现一个客户端进行负载均衡,然后开发多几个服务端来抗住高并发等等类似的设想。
完!