我的Netty笔记
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.shinho</groupId>
<artifactId>kylinstore</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>kylinstore</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jackson.version>2.5.0</jackson.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency> <!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 格式化对象,方便输出日志 --> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end --> <dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.27-incubating</version>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>0.2.9</version>
</dependency> <dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId> <!-- Use 'netty-all' for 4.0 or above -->
<version>4.1.23.Final</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>dsp</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
入口文件
package com.shinho.kylinstore; import javax.xml.ws.spi.http.HttpHandler; import io.netty.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.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler; import com.shinho.kylinstore.http.*; public class HttpServer { public static void main(String[] args) throws Exception {
int port = 8083;
new HttpServer().run(port);
} public void run(final 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<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch)
throws Exception { // HTTP请求消息解码器
ch.pipeline().addLast("http-decoder", new HttpRequestDecoder()); /*
* HttpObjectAggregator解码器
* 将多个消息转换为单一的FullHttpRequest或FullHttpResponse对象
*/
ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); //HTTP响应编码器,对HTTP响应进行编码
ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); //ChunkedWriteHandler的主要作用是支持异步发送大的码流,但不占用过多的内存,防止JAVA内存溢出
ch.pipeline().addLast("http-chunked",
new ChunkedWriteHandler()); ch.pipeline().addLast("httpServerHandler", new HttpServerHandler());
}
});
ChannelFuture future = b.bind("localhost", port).sync();
System.out.println("HTTP Server startup.");
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
请求处理文件
package com.shinho.kylinstore.http; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil; public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> { @Override
protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception {
//
if (!request.decoderResult().isSuccess()) {
sendError(context, HttpResponseStatus.BAD_REQUEST);
return;
} //
if (request.method() != HttpMethod.GET) {
sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED);
return;
} FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.content().writeInt(100);
context.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
if (ctx.channel().isActive()) {
sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
} private static void sendError(ChannelHandlerContext ctx,
HttpResponseStatus status) {
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,status,
Unpooled.copiedBuffer("Failure: " + status.toString()+ "\r\n", CharsetUtil.UTF_8));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
}
我的Netty笔记的更多相关文章
- Netty笔记
1 基本介绍 Bootstrap Netty应用程序通过设置 bootstrap(引导)类开始,该类提供了一个用于应用程序网络层配置的容器.Bootstrap有两种类型,一种是用于客户端的Bootst ...
- Netty笔记--ByteBuf释放
参考资料:http://www.maljob.com/pages/newsDetail.html?id=394 参考资料:http://www.blogjava.net/liuguly/archive ...
- Netty笔记——技术点汇总
目录 · Linux网络IO模型 · 文件描述符 · 阻塞IO模型 · 非阻塞IO模型 · IO复用模型 · 信号驱动IO模型 · 异步IO模型 · BIO编程 · 伪异步IO编程 · NIO编程 · ...
- Netty 笔记
1.Netty 是一款异步的事件驱动的网络应用程序框架,支持快速地开发可维护的高性能的面向协议的服务器和客户端. 2.早期Java API 使用的阻塞函数 // 创建一个新的ServerSocket, ...
- netty笔记(一)--Demo
Netty是一个Java开源框架,用于传输数据.由server和client组成,封装了Java nio,支持TCP, UDP等协议.这里写了一Demo EchoClientHandler.java ...
- netty笔记-:Channel与ChannelHandlerContext执行write方法的区别
在netty中有我们一般有两种发送数据的方式,即使用ChannelHandlerContext或者Channel的write方法,这两种方法都能发送数据,那么其有什么区别呢.这儿引用netty文档 ...
- netty笔记-:EpollEventLoopGroup:Caused by: java.lang.ExceptionInInitializerError:Caused by: java.lang.IllegalStateException: Only supported on Linux
今天在翻看netty的源码的时候发现netty对EventLoopGroup的实现有不止常用的NIOEventLoopGroup ,一共有以下几种. EpollEventLoopGroup NioEv ...
- Netty学习笔记(一)
学习圣思园Netty笔记,个人理解 2.netty宏观理解-本节内容: 1.阶段性事件驱动,一个请求分为若干阶段处理,每个阶段根据情况合理分配线程去处理,各阶段间通信采用异步事件驱动方式. 2.net ...
- Netty入门4之----如何实现长连接
前面三章介绍了Netty的一些基本用法,这一章介绍怎么使用Netty来实现一个简单的长连接demo. 关于长连接的背景知识,可以参考<如何使用Socket实现长连接> 一个简单的长 ...
随机推荐
- Windows 下使用nginx命令启动
http://wanganwu.blog.163.com/blog/static/7788722012322111417966/ Windows下Nginx的启动.停止等命令 在Windows下使用N ...
- SEO:网站优化内容
一.内部优化 (1)meta标签优化:例如:TDK等的优化: 首页:网站名称 或者 网站名称_提供服务介绍or产品介绍 . 频道页:频道名称_网站名称. 文章 ...
- HTML+CSS之background
第一个专题--background属性 今天写一下background属性,具体如下: 1.background-color:默认值:transparent,这是我们在做网页时,经常使用的属性,较为简 ...
- 微信导出群记录V3.0
一.序 导出东北师范大学2017级软件工程微信群的聊天记录,形式不限,但需要包含文字.图片和链接,不允许截图. 聊天记录的时间段为2017年11月3日12:00起至2018年1月3日12:00. 二. ...
- 关于”铁大吃什么“的nabcd的分析
Need: 为那些饥肠辘辘而又囊中羞涩的铁大同学提供最新最全的美食信息. Approach: 跑遍铁大所有角落,收集所有关于美食的信息,主要是价格口味方面,口味方面会通过学生的打分来数量化,建立一个库 ...
- freemarker的template用法
package cn.itcast.ssm.util; import com.alibaba.fastjson.JSONObject; import freemarker.cache.StringTe ...
- java实现各种排序算法
java实现各种排序算法 import java.util.Arrays; public class SomeSort { public static void main(String[] args) ...
- javascript 日常
$('#code').bind('keypress', function (e) { //绑定回车处理 ) { console.log($("#code")); } }); $.a ...
- C++学习(三十二)(C语言部分)之 栈
栈测试代码笔记如下: #include<stdio.h> #include<string.h> #include <stdlib.h> #define SIZE 1 ...
- 《DSP using MATLAB》Problem 5.6
频率采样定理是这样的: 由上述定理可知,一个有限长序列(假设为N)的DTFT等间隔采样,采样数至少大于等于N. 代码: %% +++++++++++++++++++++++++++++++++++++ ...